我是 JavaScript 新手,在包含此关键字时无法理解箭头函数和普通函数之间的区别,以下是我从 MDN 中读取的示例:
var obj = { // does not create a new scope
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
在这个例子中,箭头函数 b() 不能访问对象中的 i 属性,因为它引用了窗口
var obj = {
count : 10,
doSomethingLater : function(){ // of course, arrow functions are not suited for methods
setTimeout( () => { // since the arrow function was created within the "obj", it assumes the object's "this"
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater(); //log 11 on the console
但是,在第二个示例中,箭头函数中的代码可以访问 count 属性。这两个函数都在对象中定义,但只有第二个函数可以访问对象的属性,有人能给我一些提示吗?提前致谢!