JS 对象方法与 this 绑定
对象方法
对象方法是 对象中定义的函数,可以通过对象调用。
js
const person = {
name: "Alice",
greet() {
console.log(`Hello, ${this.name}`);
}
};
person.greet(); // Hello, Alice
this指向调用方法的对象(这里是person)
this 的绑定规则
- 默认绑定(全局上下文)
js
function show() {
console.log(this);
}
show(); // 浏览器:window / Node:global
- 在严格模式下,
this为undefined
- 隐式绑定(对象调用)
js
const obj = {
name: "Bob",
greet() {
console.log(this.name);
}
};
obj.greet(); // Bob
this指向调用该方法的对象
- 显式绑定(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
call、apply立即调用函数,指定thisbind返回一个新函数,绑定this
- 箭头函数绑定
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,继承自外层 - 可以使用
call、apply、bind显式绑定this - 赋值给变量调用方法会丢失原对象绑定,需要注意