apply、bind、call改变this指向——JavaScript
·
目录
1.this指向
普通函数中的 this 一般指向调用它的元素(谁调用指向谁);箭头函数没有自己的this,但会默认绑定外层的this,并且箭头函数的 this 在定义时就确定了,之后永远不变。
const obj = {
name: 'Alice',
normalFn: function () {
console.log('normal:', this.name); // 这里的 this 是 obj
},
arrowFn: () => {
console.log('arrow:', this.name); // 这里的 this 是外层作用域的 this
}
};
obj.normalFn(); // 输出:normal: Alice
obj.arrowFn(); // 输出:arrow: undefined(外层是全局作用域)
2.call()
call 是函数对象的一个方法,用于显式指定函数执行时的 this 值。并且传递的参数形式是以逗号进行分隔,语法:func.call(thisArg,arg1,arg1,......)
function showName() {
console.log(this.name);
}
const person = { name: 'Alice' };
showName.call(person); // 输出:Alice,函数并无参数所以无需传参
3.bind()
bind 方法不用调用函数,就能改变函数内部的this指向(指 bind 执行时不会立刻跑函数体里的代码,它只是生成了一个新函数,这个新函数内部已经把 this 永久锁定不能再次修改)。并且传递的参数形式是以逗号进行分隔,语法:func.bind(thisArg,arg1,arg1,......)。
function f() { console.log(this.x); }
const obj = { x: 1 };
const newF = f.bind(obj); // 什么都没打印
// 只是生成了一个“this 被锁成 obj”的新函数 newF
newF(); // 现在才打印 1
4.apply()
apply 方法调用函数,同时指定被调用函数的this值。并且传递的参数形式使用一个数组包裹起来,语法:func.apply(thisArg,[arg1,arg1,......])。
const obj = {
age : 18
}
function fn(x,y) {
console.log(this)//此时this指向window
}
fn.apply(obj,[1,2])//此时this指向obj,并且第二个参数是一个数组
更多推荐
所有评论(0)