# 对象方法

let user = {
    sayHi: function() {
        alert("Hello");
    }
};

let user = {
    sayHi() {
        alert("Hello");
    }
};

# 方法中的 “this”

this 的值就是调用该方法的对象。

let user = {
    name: "John",
    age: 30,
    sayHi() {
        alert(this.name);
    }
};
user.sayHi();
user.sayHi.call(user); // 指定 this
user.sayHi.apply(user); // 指定 this
user.sayHi.bind(user)(); // 指定 this

# 函数中的 “this”

this 的值是在代码运行时计算出来的,它取决于代码上下文。

相同的函数被分配给不同的对象,在调用中有着不同的 “this” 值。

function sayHi() {
    alert( this.name );
}

在没有对象的情况下调用

  • 严格模式this == undefined
  • 非严格模式this == window

# 箭头函数没有自己的 “this”

我们在箭头函数中引用 thisthis 值取决于外部“正常的”函数。

let user = {
    firstName: "Ilya",
    sayHi() {
        let arrow = () => alert(this.firstName);
        arrow();
    }
};
user.sayHi();