js中的call()和apply()

来源:互联网 发布:中国食物浪费数据 编辑:程序博客网 时间:2024/06/09 17:14

面试时两次遇到这个问题,第一次不会,回来查查资料知道了大概,没想过几天再次见到,依旧不会,我这脑子,所以,这次自己查资料看高手的总结,在这记录一下:

1、call()方法定义:

a、定义:调用一个对象的一个方法,以另一个对象替换当前对象。语法为call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) 。

b、说明:call方法可以用来代替另一个对象调用一个方法。可将一个函数的对象上下文从初始的上下文改为由thisObj指定的新对象。如果没有提供thisObj参数,那么Global对象将被用作thisObj。

call()方法示例:

<script>        window.color = 'red';        document.color = 'yellow';        var s1 = {color: 'blue' };        function changeColor(){            console.log(this.color);        }        changeColor.call();         //red (默认传递参数)        changeColor.call(window);   //red        changeColor.call(document); //yellow        changeColor.call(this);     //red        changeColor.call(s1);       //blue    </script>    //例2    var Pet = {        words : '...',        speak : function (say) {            console.log(say + ''+ this.words)        }    }    Pet.speak('Speak'); // 结果:Speak...    var Dog = {        words:'Wang'    }    //将this的指向改变成了Dog    Pet.speak.call(Dog, 'Speak'); //结果: SpeakWang


c、转载的例子:

1》、

function add(a,b){    alert(a+b);}function sub(a,b){    alert(a-b);}add.call(sub,3,1); 
这个案例的意思就是用add来代替sub,add.call(sub,3,1)===add(3,1),结果为:alert(4).

2》、

function Animal(){      this.name = "Animal";      this.showName = function(){          alert(this.name);      }  }  function Cat(){      this.name = "Cat";  }   var animal = new Animal();  var cat = new Cat();    //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。  //输入结果为"Cat"  animal.showName.call(cat,",");  //animal.showName.apply(cat,[]);
call的意思是把animal的方法用到cat上执行,原来cat上是没有showName()方法的,现在是把animal的showName()方法放到cat上执行,所以,this.name的结果是Cat。

3》、实现继承

 function Animal(name){         this.name = name;         this.showName = function(){             alert(this.name);         }     }        function Cat(name){       Animal.call(this, name);   }        var cat = new Cat("Black Cat");    cat.showName();
Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么 Cat中不就有Animal的所有属性和方法了吗,Cat对象就能够直接调用Animal的方法以及属性了.结果当然就是黑猫了。

4》、多重继承

function Class10(){    this.showSub = function(a,b)    {        alert(a-b);    }}function Class11(){    this.showAdd = function(a,b)    {        alert(a+b);    }}function Class2(){    Class10.call(this);    Class11.call(this);}
很简单,使用两个call就实现多重继承了。


2、apply()方法和定义:

a、定义:应用某一个对象的一个方法,用另一个对象替换当前对象。语法为:apply([thisObj[,argArray]])。

b、说明:如果argArray不是一个有效的数组或者不是arguments对象,那将导致一个TypeError。如果没有提供argArray和thisObj任何一个参数,那么Global对象将被用作thisObj,并且无法被传递任何参数。
apply()方法示例:
<script>        window.number = 'one';        document.number = 'two';        var s1 = {number: 'three' };        function changeColor(){            console.log(this.number);        }        changeColor.apply();         //one (默认传参)        changeColor.apply(window);   //one        changeColor.apply(document); //two        changeColor.apply(this);     //one        changeColor.apply(s1);       //three    </script>    //例2    function Pet(words){        this.words = words;        this.speak = function () {            console.log( this.words)        }    }    function Dog(words){        //Pet.call(this, words); //结果: Wang       Pet.apply(this, arguments); //结果: Wang    }    var dog = new Dog('Wang');    dog.speak();

3、相同点:
这两个方法的作用都是在特定的作用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的作用域。
一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。
4、不同点:接收参数的方式不同。
apply()方法接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。
call()方法第一个参数和apply()方法的一样,但是传递给函数的参数必须列举出来。
1、function add(c,d){        return this.a + this.b + c + d;    }    var s = {a:1, b:2};    console.log(add.call(s,3,4)); // 1+2+3+4 = 10    console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14 
2、<script>        window.firstName = "Cynthia";         window.lastName = "_xie";        var myObject = {firstName:'my', lastName:'Object'};        function getName(){            console.log(this.firstName + this.lastName);        }        function getMessage(sex,age){            console.log(this.firstName + this.lastName + " 性别: " + sex + " age: " + age );        }        getName.call(window); // Cynthia_xie        getName.call(myObject); // myObject        getName.apply(window); // Cynthia_xie        getName.apply(myObject);// myObject        getMessage.call(window,"女",21); //Cynthia_xie 性别: 女 age: 21        getMessage.apply(window,["女",21]); // Cynthia_xie 性别: 女 age: 21        getMessage.call(myObject,"未知",22); //myObject 性别: 未知 age: 22        getMessage.apply(myObject,["未知",22]); // myObject 性别: 未知 age: 22    </script>