JS中的call()和apply()方法详解

来源:互联网 发布:java 堆内存 编辑:程序博客网 时间:2024/05/19 06:49

参考文章:JS中的call()和apply()方法

1.方法定义

call()方法
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
apply()方法
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

2.使用例子

function sayColor(sPrefix,sSuffix){    alert(sPrefix+this.color+sSuffix);}var obj=new Object();obj.color="blue";sayColor.call(obj,"This color is "," a very nice color indeed.");

1.png

function Person(name,age){    this.name=name;    this.age=age;}function Student(name,age,grade){    Person.apply(this,arguments);    this.grade=grade;}var student=new Student("qian",21,"一年级");alert("name:"+student.name+" age:"+student.age+" grade:"+student.grade);

2.png

3.深入理解

a

function add(a,b){    alert(a+b);}function sub(a,b){    alert(a-b);}add.call(sub,12,5);//17

这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4); // 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。
b

 function Animal(){    this.name="Animal";    this.showName=function(){        alert(this.name);    }}function Cat(){    this.name="cat";}var animal=new Animal();var cat=new Cat();animal.showName.call(cat,",");//cat//animal.showNamw.call(cat,[]);

call 的意思是把 animal 的方法放到cat上执行,原来cat是没有showName() 方法,现在是把animal 的showName()方法放到 cat上来执行,所以this.name 应该是 Cat
c

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的方法以及属性了.
d

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 就实现多重继承了。

与this结合使用的用法

call和apply都可以改变this指向。

var test = "Tony";var myobj = {    test: "Tom"};function doSomething() {    alert(this.test);}doSomething();=doSomething.call(); // 弹出 window.test   ,即 "Tony"doSomething.call(myobj); // 这个时候,doSomething函数里的this指向 myobj,//所以弹出的是 myobj.test 即 "Tom"

总结

注意到,call()与apply()的区别:功能一样。第二个参数形式不一样。call传递多个参数,是任意形式。apply第二个参数必须是数组形式。
用代码来理解它们区别最好:

a.call(b,2,3); ==> a.apply(b,[2,3]);//数组形式传入

就是利用了apply参数是数组的特性。结合函数的隐性参数,都会自动保存在arguments数组中。这样,使用apply的方式:

this.initialize.apply(this, arguments);

可以直接将当前函数的arguments数组作为apply的第二个参数传入,不需要转化。

原创粉丝点击