通过实例理解javascript 的call()与apply()

来源:互联网 发布:网络灯亮着但是没网络 编辑:程序博客网 时间:2024/05/16 16:00

url:http://www.iteye.com/topic/599108

call方法: 
语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) 
定义:调用一个对象的一个方法,以另一个对象替换当前对象。 
说明: 
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 

apply方法: 
语法:apply([thisObj[,argArray]]) 
定义:应用某一对象的一个方法,用另一个对象替换当前对象。 
说明: 
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。 

//=============================================================================

如果没接触过动态语言,以编译型语言的思维方式去理解javaScript将会有种神奇而怪异的感觉,因为意识上往往不可能的事偏偏就发生了,甚至觉得不可理喻.如果在学JavaScript这自由而变幻无穷的语言过程中遇到这种感觉,那么就从现在形始,请放下的您的”偏见”,因为这对您来说绝对是一片新大陆,让JavaScrip

好,言归正传,先理解JavaScrtipt动态变换运行时上下文特性,这种特性主要就体现在apply, call两个方法的运用上.

区分apply,call就一句话,

  foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)

 

call, apply都属于Function.prototype的一个方法,它是JavaScript引擎内在实现的,因为属于Function.prototype,所以每个Function对象实例,也就是每个方法都有call, apply属性.既然作为方法的属性,那它们的使用就当然是针对方法的了.这两个方法是容易混淆的,因为它们的作用一样,只是使用方式不同.

相同点:两个方法产生的作用是完全一样的

不同点:方法传递的参数不同

那什么是方法产生的作用,方法传递的参数是什么呢?

我们就上面的foo.call(this, arg1, arg2, arg3)展开分析.

foo是一个方法,this是方法执行时上下文相关对象,arg1, arg2, arg3是传给foo方法的参数.这里所谓的方法执行时上下文相关对象, 如果有面向对象的编程基础,那很好理解,就是在类实例化后对象中的this.

在JavaScript中,代码总是有一个上下文对象,代码处理该对象之内. 上下文对象是通过this变量来体现的, 这个this变量永远指向当前代码所处的对象中.

为了更好的领会这this是什么,举个例子. 

  代码

       var A=function(){

             message:null,

             getMessage:function(){

                     return this.message;

             }

       } ;     

     var B=function(){

             message:null,

             setMessage:function(msg){

                     this.message=msg;

             }

       };

   var a=new A();

 题外话:javascript对象所有属性都是公开的(public),没私有(private)之说,所以也可直接访问message属性

 

alert(a.message);

可见,A, B类都有一个message属性(面向对象中所说的成员),A有获取消息的getMessage方法,B有设置消息的setMessage方法,下面来显示call的威力.

  //创建一个B类实例对象

var b = new B();
//给对象a动态指派b的setMessage方法,注意,a本身是没有这方法的!
b.setMessage.call(a, "a的消息");
//下面将显示"a的消息"
alert(a.getMessage());
//给对象b动态指派a的getMessage方法,注意,b本身也是没有这方法的!

 

 这就是动态语言 JavaScript call的威力所在!

简直是”无中生有”,对象的方法可以任意指派,而对象本身一直都是没有这方法的,注意是指派,通俗点就是,方法是借给另一个对象的调用去完成任务,原理上是方法执行时上下文对象改变了.

所以 b.setMessage.call(a, “a的消息”); 就等于用a作执行时上下文对象调用b对象的setMessage方法,而这过程中与b一点关系都没有, 作用等效于a.setMessage( “a的消息”);

因为apply与call产生的作用是一样的,可以说

call, apply作用就是借用别人的方法来调用,就像调用自己的一样.

好,理解了call, apply相同处—–作用后,再来看看它们的区别,看过上面例子,相信您大概知道了.

从 b.setMessage.call(a, “a的消息”) 等效于 a.setMessage( “a的消息”) 可以看出, “a的消息”在call中作为一个参数传递,

那么在apply中是怎么表示的呢,直接解释说不清楚,apply要结合应用场景才一目了然.我们来设计一个应用场景:
 

view source
01function print(a, b, c, d){
02alert(a + b + c + d);
03}
04function example(a, b , c , d){
05//用call方式借用print,参数显式打散传递
06print.call(this, a, b, c, d);
07//用apply方式借用print, 参数作为一个数组传递,
08//这里直接用JavaScript方法内本身有的arguments数组
09print.apply(this, arguments);
10//或者封装成数组
11print.apply(this, [a, b, c, d]);
12}
13//下面将显示”背光脚本”
14example(”背” , “光” , “脚”, “本”);

在这场景中, example方法内,a, b, c, d作为方法传递的参数, 方法分别运用了apply, call去借print方法来调用,

最后一句由于直接调用example方法, 所以在该方法中的上下文对象this就是window对象.

所以,call, apply方法它们除了第一个参数,即执行时上下文对象相同外,call方法的其它参数将依次传递给借用的方法作参数,而apply就两个参数,第二个参数为一个数组传递.所以可以说成

call, apply方法区别是,从第二个参数起, call方法参数将依次传递给借用的方法作参数, 而apply直接将这些参数放到一个数组中再传递, 最后借用方法的参数列表是一样的.

 

应用场景:

当参数明确时可用call, 当参数不明确时可用apply给合arguments
 

1//例
2print.call(window, “背” , “光” , “脚”, “本”);
3//foo参数可能为多个
4function foo(){
5print.apply(window, arguments);
6}
 //=============================================================================


/** * Constructor: OpenLayers.Class * Base class used to construct all other classes. Includes support for  *     multiple inheritance.  *      * This constructor is new in OpenLayers 2.5.  At OpenLayers 3.0, the old  *     syntax for creating classes and dealing with inheritance  *     will be removed. *  * To create a new OpenLayers-style class, use the following syntax: * (code) *     var MyClass = OpenLayers.Class(prototype); * (end) * * To create a new OpenLayers-style class with multiple inheritance, use the *     following syntax: * (code) *     var MyClass = OpenLayers.Class(Class1, Class2, prototype); * (end) *  * Note that instanceof reflection will only reveal Class1 as superclass. * */OpenLayers.Class = function() {    var len = arguments.length;    var P = arguments[0];    var F = arguments[len-1];    var C = typeof F.initialize == "function" ?        F.initialize :        function(){ P.prototype.initialize.apply(this, arguments); };    if (len > 1) {        var newArgs = [C, P].concat(                Array.prototype.slice.call(arguments).slice(1, len-1), F);        OpenLayers.inherit.apply(null, newArgs);    } else {        C.prototype = F;    }    return C;};

/** * Property: isPrototype * *Deprecated*.  This is no longer needed and will be removed at 3.0. */OpenLayers.Class.isPrototype = function () {};/** * APIFunction: OpenLayers.create * *Deprecated*.  Old method to create an OpenLayers style class.  Use the *     <OpenLayers.Class> constructor instead. * * Returns: * An OpenLayers class */OpenLayers.Class.create = function() {    return function() {        if (arguments && arguments[0] != OpenLayers.Class.isPrototype) {            this.initialize.apply(this, arguments);        }    };};/** * APIFunction: inherit * *Deprecated*.  Old method to inherit from one or more OpenLayers style *     classes.  Use the <OpenLayers.Class> constructor instead. * * Parameters: * class - One or more classes can be provided as arguments * * Returns: * An object prototype */OpenLayers.Class.inherit = function (P) {    var C = function() {       P.call(this);    };    var newArgs = [C].concat(Array.prototype.slice.call(arguments));    OpenLayers.inherit.apply(null, newArgs);    return C.prototype;};/** * Function: OpenLayers.inherit * * Parameters: * C - {Object} the class that inherits * P - {Object} the superclass to inherit from * * In addition to the mandatory C and P parameters, an arbitrary number of * objects can be passed, which will extend C. */OpenLayers.inherit = function(C, P) {   var F = function() {};   F.prototype = P.prototype;   C.prototype = new F;   var i, l, o;   for(i=2, l=arguments.length; i<l; i++) {       o = arguments[i];       if(typeof o === "function") {           o = o.prototype;       }       OpenLayers.Util.extend(C.prototype, o);   }};/** * APIFunction: extend * Copy all properties of a source object to a destination object.  Modifies *     the passed in destination object.  Any properties on the source object *     that are set to undefined will not be (re)set on the destination object. * * Parameters: * destination - {Object} The object that will be modified * source - {Object} The object with properties to be set on the destination * * Returns: * {Object} The destination object. */OpenLayers.Util = OpenLayers.Util || {};OpenLayers.Util.extend = function(destination, source) {    destination = destination || {};    if (source) {        for (var property in source) {            var value = source[property];            if (value !== undefined) {                destination[property] = value;            }        }        /**         * IE doesn't include the toString property when iterating over an object's         * properties with the for(property in object) syntax.  Explicitly check if         * the source has its own toString property.         */        /*         * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative         * prototype object" when calling hawOwnProperty if the source object         * is an instance of window.Event.         */        var sourceIsEvt = typeof window.Event == "function"                          && source instanceof window.Event;        if (!sourceIsEvt           && source.hasOwnProperty && source.hasOwnProperty("toString")) {            destination.toString = source.toString;        }    }    return destination;};