JavaScript 中修改 this 指向的 4 种方法
- 使用 call(), apply(), bind() 方法
这是最常见的方法,通过这三个函数可以将函数体内的 this 关键字指向任何一个对象。
- call(): 立即执行函数,并改变函数内部的 this 指向,可以传递多个参数。
- apply(): 立即执行函数,并改变函数内部的 this 指向,可以传递一个数组。
- bind(): 返回一个新函数,并改变新函数内部的 this 指向,不立即执行。
- 使用箭头函数
箭头函数的 this 指向是定义时的上下文,而不是运行时的上下文,因此无法修改 this 指向。
- 使用 ES6 的解构赋值
ES6 的解构赋值可以将 this 指向改变到任何一个对象。
let obj = {
name: '张三',
sayName: function() {
let { name } = this;
console.log(name);
}
};
let obj2 = { name: '李四' };
obj.sayName.call(obj2); // 李四
- 使用对象的方法
对象的方法可以改变函数内部的 this 指向。
let obj = {
name: '张三',
sayName: function() {
console.log(this.name);
}
};
let obj2 = { name: '李四' };
obj2.sayName = obj.sayName;
obj2.sayName(); // 李四
原文地址: https://www.cveoy.top/t/topic/lVDT 著作权归作者所有。请勿转载和采集!