var person = {
name: "Nicholas",
sayName() {
console.log(this.name);
}
};
var person = {
name: "Nicholas",
sayName:()=> {
console.log(this.name);
}
};这两种写法有什么区别?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
this的不一样,箭头函数不会产生新的this
区别在于第一个 this 指向 person,也就是你调用 person.sayName() 时可以得到 Nicholas,第二个实际上可以看作
var person = { name: "Nicholas", sayName: function() { console.log(this.name); } };它的 this 实际上指向的是 window 而不是 person,所以取不到对应的 name 值