理解js中的this指向以及call,apply,bind方法

时间:2023-01-01 09:33:19

 

<script>
function a(){
    var user = "追梦子";
    console.log(this.user); //undefined
    console.log(this); //Window
}
a();
</script>

按照我们上面说的函数中的this指向的是最终调用并执行它的对象,(切记this指向的是最终执行该函数的对象)这里的函数a实际是被Window对象所点出来的,Window对象表示的是浏览器打开的窗口。例如上面的Window 指的是这个窗口file:///C:/Users/yanyanshan/Desktop/test/parent.html下面的代码就可等价于上面的代码alert也是window的一个属性,也是window点出来的。

 

<script>

function a(){

    var user = "追梦子";

    console.log(this.user); //undefined

console.log(this); //Window}

window.a();

window.alert(“追门子”);

</script>

 

再看一个例子

var o = {

    user:"追梦子",

    fn:function(){

        console.log(this.user);  //追梦子    }

}

o.fn();

 

这里的this指向的是对象o,因为你调用这个fn是通过o.fn()执行的,那自然指向就是对象o,这里再次强调一点,函数中的this指向在函数创建的时候是决定不了的,在调用执行的时候才能决定,谁是最后调用并执行该函数的就指向谁,一定要搞清楚这个。

var o = {

    user:"追梦子",

    fn:function(){

        console.log(this.user); //追梦子    }

}

window.o.fn();

 

windowjs中的全局对象,我们创建的变量实际上是给window添加属性,所以这里可以用windowo对象。但这里最后调用fn函数的是o对象,因此this自然指向的是o

var o = {

    a:10,

    b:{

        a:12,

        fn:function(){

            console.log(this.a); //12        }

    }

}

o.b.fn();

 

以上的代码打印出来的12,因为这里最后调用fn函数的是b对象,因此执行函数的时候this指向的是b对象。

var o = {

    a:10,

    b:{

        fn:function(){

            console.log(this.a); //undefined        }

    }

}

o.b.fn();

 

这里也是最后调用函数的是b对象,因为b对象中没有a属性,因此打印出来的是undefined

再看一个例子

var o = {

    a:10,

    b:{

        a:12,

        fn:function(){

            console.log(this.a); //undefined

            console.log(this); //window        }

    }

}

var j = o.b.fn;

j();

j()===window.j();

 

这里的this指向的是window,为什么呢?我们说this指向的是最终调用并且执行该函数的对象。以上b虽然是最后调用fn函数的对象,但是它是把函数赋给了变量j,并没有执行该函数。而函数最终执行的时候是window调用的。

 

但有时候,我们想把某个对象的函数保存到一个变量中,通过该变量来执行函数,希望执行该函数的不是window对象。那么就要以下的方法

 

JavaScript 中,call、apply 和 bind 是 Function 对象自带的三个方法,这三个方法的主要作用是改变函数中的 this 指向,

1、call(thisArgsargs1,args2,……)

 

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this.user); //追梦子

    }

}var b = a.fn;

b.call(a);

 

 

通过在call方法,给第一个参数指定要把b添加到哪个环境中,也就是指定执行b函数的是哪个对象。那么函数中的this就会指向那个对象。

call方法除了第一个参数以外还可以添加多个参数,后面的参数将会被传入调用函数中。如下:

var a = {

    user:"追梦子",

    fn:function(e,ee){

        console.log(this.user); //追梦子

        console.log(e+ee); //3

    }

}var b = a.fn;

b.call(a,1,2);

 

2、apply(thisArgs[args1args2,……])

apply方法和call方法有些相似,它也可以改变this的指向

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this.user); //追梦子

    }

}var b = a.fn;

b.apply(a);

 

同样apply也可以有多个参数,但是不同的是,第二个参数必须是一个数组,如下:

var a = {

    user:"追梦子",

    fn:function(e,ee){

        console.log(this.user); //追梦子

        console.log(e+ee); //11

    }

}var b = a.fn;

b.apply(a,[10,1]);

 

或者

var a = {

    user:"追梦子",

    fn:function(e,ee){

        console.log(this.user); //追梦子

        console.log(e+ee); //520

    }

}var b = a.fn;var arr = [500,20];

b.apply(a,arr);

 

//注意如果call和apply的第一个参数写的是null,那么this指向的是window对象

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this); //Window {external: Object, chrome: Object, document: document, a: Object, speechSynthesis: SpeechSynthesis…}

    }

}

var b = a.fn;

b.apply(null);

 

3、bind(thisArgs args1args2..)

bind方法和call、apply方法有些不同,但是不管怎么说它们都可以用来改变this的指向。调用 call 或 apply 都会自动执行对应的函数,而 bind 不会执行对应的函数,实际上bind方法返回的是一个修改过后的函数。

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this.user);

    }

}var b = a.fn;

b.bind(a);

 

以上没有打印出来任何的东西。

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this.user);

    }

}

var b = a.fn;

var c = b.bind(a);

console.log(c); //打印function() { [native code] }

 

bind方法返回的是一个修改过后的函数,因此打印c的时候是一个函数

那么我们现在执行一下函数c看看,能不能打印出对象a里面的user

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this.user); //追梦子

    }

}

var b = a.fn;

var c = b.bind(a);

c();

ok,可以打印出来。同样bind也可以有多个参数,并且参数可以执行的时候再次添加,但是要注意的是,参数是按照形参的顺序进行的。

var a = {

    user:"追梦子",

    fn:function(e,d,f){

        console.log(this.user); //追梦子

        console.log(e,d,f); //10 1 2

    }

}

var b = a.fn;

var c = b.bind(a,10);

c(1,2);

 

注意看以上的结果。

bind是ES5 新增的一个方法,粗略一看,bind 似乎比call/apply 要落后一些,那ES5为什么还要引入bind 呢?

其实,ES5引入 bind 的真正目的是为了弥补 call/apply 的不足,由于 call/apply 会对目标函数自动执行,从而导致它无法在事件绑定函数中使用,因为事件绑定函数不需要我们手动执行,它是在事件被触发时由JS 内部自动执行的。而 bind 在实现改变函数 this 的同时又不会自动执行目标函数,因此可以完美的解决上述问题,看一个例子就能明白:

 

var obj = {name:'onepixel'};

 

/**

 * 给document添加click事件监听,并绑定onClick函数

 * 通过bind方法设置onClick的this为obj,并传递参数p1,p2

 */

document.addEventListener('click',onClick.bind(obj,'p1','p2'),false);

 

//当点击网页时触发并执行

function onClick(a,b){

    console.log(

            this.name, //onepixel

            a, //p1

            b  //p2

    )

}

 

 


一旦函数通过
bind传递了有效的this对象,则该函数在运行期的this将指向这个对象,即使通过callapply来试图改变this的指向也是徒劳的。当点击网页时,
onClick 被触发执行,输出onepixel p1 p2, 说明 onClick 中的 this 被 bind 改变成了obj 对象。

应用场景一:继承

大家知道,JavaScript中没有诸如Java、C# 等高级语言中的extend 关键字,因此JS 中没有继承的概念,如果一定要继承的话,call 和 apply 可以实现这个功能:

 

function Animal(name,weight){

   this.name = name;

   this.weight = weight;

}

 

function Cat(){

    Animal.call(this,'cat','50');

  //Animal.apply(this,['cat','50']);

 

   this.say = function(){

      console.log("I am " + this.name+",my weight is " + this.weight);

   }

}

 

var cat = new Cat();

cat.say();//I am cat,my weight is 50

 

 


 
当通过
new 运算符产生了cat 时,Cat中的 this 就指向了cat对象,而继承的关键是在于Cat中执行了Animal.call(this,'cat','50') 这句话,在call中将this作为thisArgs参数传递,于是Animal 方法中的 this 就指向了Cat中的 this,而 cat 中的 this 指向的是 cat 对象,所以Animal 中的 this 指向的就是 cat 对象,在 Animal 中定义了name 和 weight 属性,就相当于在 cat 中定义了这些属性,因此 cat 对象便拥有了Animal 中定义的属性,从而达到了继承的目的。