在JavaScript中,可以使用call()、apply()或bind()来改变函数的this指向。
1.call(): 通过调用函数并传入新的上下文对象作为参数,将函数内部的this关键字指向该对象。示例代码如下所示
function greet(name) {
console.log("Hello " + name);
}
var person = {
name: 'Alice'
};
greet.call(person, 'Bob'); // 输出结果为:"Hello Bob"
call() 可以改变函数内的this 指向,可以调用函数
<script>
function Person() {
this.name = 'kobe';
this.sex = '男';
this.age = '41';
}
function Star(name,sex,age) {
Person.call(this,name,sex,age); //call 改变了this指向
console.log(this.name);
console.log(this.sex);
console.log(this.age);
}
new Star(); // 实例化对象
</script>
2.apply(): 与call()类似,也是通过调用函数并传入新的上下文对象作为参数,不同之处在于apply()接收一个包含多个参数的数组而非单个参数。示例代码如下所示:
function sum(a, b) {
return a + b;
}
console.log(sum.apply(null, [3, 5])); // 输出结果为:8
apply() 方法可以改变this指向,也会调用函数 和 call() 不同点是 apply() 的参数必须是数组或者伪数组的形式
<script>
function Person() {
this.name = 'kobe';
this.sex = '男';
this.age = '41';
}
function Star(arr) {
console.log(this); // 这个this指向 Star
console.log(arr);
}
Star.apply(Person,['科比']) // 改变this指向之后,变成指向Person ,且参数要是数组形式
</script>
3.bind(): 创建一个新的函数,其this值被永久地设置为提供的对象。原始函数会保持不变。示例代码如下所示:
function greet(name) {
console.log("Hello " + this.name + ", " + name);
}
var person = {
name: 'Alice'
};
var boundFunc = greet.bind(person);
boundFunc('Bob'); // 输出结果为:"Hello Alice, Bob"
bind() 方法 可以改变this指向,但不会调用原来的函数,返回的是改变this指向之后的产生的新函数
<script>
function Person() {
this.name = 'kobe';
this.sex = '男';
this.age = '41';
}
function Star(a,b) {
console.log(this);
console.log(a + b);
}
var fn = Star.bind(Person,1,3); // 不会调用原来的函数,产生一个新的函数(this指向改变的新函数)
fn();
</script>