对象方法与 "this"
1.对象方法
let user = {
sayHi: function() {
alert("Hello");
}
};
// 方法简写看起来更好,对吧?
let user = {
sayHi() { // 与 "sayHi: function()" 一样
alert("Hello");
}
};
2.方法中的 "this"
let user = {
name: "John",
age: 30,
sayHi() {
alert( user.name ); // 导致错误
}
};
let admin = user;
user = null; // 覆盖让其更易懂
admin.sayHi(); // 噢哟!在 sayHi() 使用了旧的变量名。错误!
//如果在 alert 中以 this.name 替换 user.name,那么代码就会正常运行。
3.箭头函数没有自己的 “this”

浙公网安备 33010602011771号