js改变this指向的三种方法

469 阅读2分钟

JavaScript改变this指向的三种方法

每个Function构造函数的原型prototype, 都有方法 call(), apply(), bind()

1. call() 方法

var Person = {
    name: "zhangsan",
    age: 19
}

function aa(x, y) {
    console.log(x + "," + y);
    console.log(this);
    console.log(this.name);
}

aa(4, 5); //this指向window--4,5  window  空

aa.call(Person, 4, 5); //this指向Person--4,5  Person{}对象  zhangsan

2. apply() 方法

apply() 与call() 非常相似, 不同之处在于提供参数的方式, apply() 使用参数数组, 而不是参数列表

var Person = {
    name: "zhangsan",
    age: 19
}

function aa(x, y) {
    console.log(x + "," + y);
    console.log(this);
    console.log(this.name);
}

aa.apply(Person, [4, 5]); //this指向Person--4,5  Person{}对象  zhangsan

3. bind() 方法

bind() 创建的是一个新的函数( 称为绑定函数), 与被调用函数有相同的函数体, 当目标函数被调用时this的值绑定到 bind() 的第一个参数上

var Person = {
    name: "zhangsan",
    age: 19
}

function aa(x, y) {
    console.log(x + "," + y);
    console.log(this);
    console.log(this.name);
}

aa.bind(Person, 4, 5); //只是更改了this指向,没有输出
aa.bind(Person, 4, 5)(); //this指向Person--4,5  Person{}对象  zhangsan

另外,我们可以存储this指向到变量中,也可改变this指向

var oDiv1 = document.getElementById("div1");
oDiv1.onclick = function () {
    var _this = this; //将this储存在变量中,而且不改变定时器的指向
    setTimeout(function () {
        console.log(_this); //注意这里是_this,而不是this-- <div id="div1">点击</div>
        console.log(this); //定时器的指向没有被改变--仍然是window
    }, 1000)
}

总结

  1. call方法在调用的时候会执行函数 第一个参数是this的指向 第二个参数以及后面的参数都是需要传的参数 返回值是原函数中定义的返回值
  2. apply方法在调用的时候也会执行函数 第一个参数是this的指向 第二个参数是数组 其中是需要传递的参数 返回值是原函数中定义的返回值
  3. bind方法在调用的时候不会执行函数 第一个参数是this的指向 第二个参数以及后面的参数都是需要传的参数 返回值是一个新的函数