跳到主要内容

JS 对象方法与 this 绑定

对象方法

对象方法是对象中定义的函数,可以通过对象调用。

js
const person = {
name: "Alice",
greet() {
console.log(`Hello, ${this.name}`);
}
};

person.greet(); // Hello, Alice
  • this 指向调用方法的对象(这里是 person

this 的绑定规则

  1. 默认绑定(全局上下文)
js
function show() {
console.log(this);
}

show(); // 浏览器:window / Node:global
  • 在严格模式下, thisundefined

  1. 隐式绑定(对象调用)
js
const obj = {
name: "Bob",
greet() {
console.log(this.name);
}
};

obj.greet(); // Bob
  • this 指向调用该方法的对象

  1. 显式绑定(call、apply、bind)
js
function greet() {
console.log(this.name);
}

const person = { name: "Charlie" };

greet.call(person); // Charlie
greet.apply(person); // Charlie
const boundGreet = greet.bind(person);
boundGreet(); // Charlie
  • callapply 立即调用函数,指定 this
  • bind 返回一个新函数,绑定 this

  1. 箭头函数绑定
js
const person = {
name: "David",
greet: () => {
console.log(this.name);
}
};

person.greet(); // undefined
  • 箭头函数没有自己的 this
  • this 从定义时的外层作用域继承

方法赋值与 this

js
const person = {
name: "Eve",
greet() { console.log(this.name); }
};

const fn = person.greet;
fn(); // undefined(默认绑定,非严格模式下是 window.name)
  • 将方法赋给变量调用, this 会丢失对象绑定

总结
  • 对象方法内部的 this 默认指向调用它的对象
  • 箭头函数不绑定自己的 this ,继承自外层
  • 可以使用 callapplybind 显式绑定 this
  • 赋值给变量调用方法会丢失原对象绑定,需要注意