对象方法与 "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”

 

posted @ 2019-08-08 17:00  C_XingM  阅读(98)  评论(0)    收藏  举报