const obj = {
name: " jsCoder",
skill: ["es6", "react", "angular"],
say: function ()
{
var that = this;
for (var i = 0, len = this.skill.length; i < len; i++)
{
setTimeout((function()
{
console.log(i);
console.log(that.skill[i]);
})(), 0)
console.log(i);
}
}
};
obj.say();
这段代码在Node里执行会报错,但可以在浏览器中执行,执行结果:
第二种写法:
const obj = {
name: " jsCoder",
skill: ["es6", "react", "angular"],
say: function () {
var that = this;
for (var i = 0, len = this.skill.length; i < len; i++) {
(function () {
var j = i;
setTimeout((function () {
console.log(j);
console.log(that.skill[j]);
}), 0)
})()
console.log(i);
}
}
};
obj.say();
为什么,立即执行函数是异步任务吗?
不负相思意
相关分类