JS中apply和call的联系和区别

以下内容翻译自stackoverflow

链接:

http://stackoverflow.com/questions/7238962/function-apply-not-using-thisarg-parameter

在AS3中,Method(方法)不同于Function(函数),Method是类的一部分,并且是和实例绑定【就是说这个类一旦实例化了,类里定义的Method会绑定这个实例】,看这个链接的第二部分关于Method,引用一部分:

Methods是类定义的functions(函数),一旦类实例化,method会绑定这个实例。函数可以声明在类外,而方法不能脱离类而单独使用。

所以,当我们创建一个MyObj类,类里所有方法绑定这个实例,这就是为什么当你想使用call或apply(的第一个参数),并没有发现this(这个指针)被重新定向为新的对象。看Bound Methods的解释细节。(随后有时间翻译一下bound methods)

看这个链接解释traits object(有时间翻译),actionscript 用来解决method,并用作背后可能会归咎于的性能原因,这个traits object和类方法都仅仅是遵从ECMAScript模式的语法糖:

var TestClass = function(data) {
    var self = this;
    this.data = data;
    this.boundWork = function() {
        return self.constructor.prototype.unboundWork.apply(self, arguments);
    };
};

TestClass.prototype.unboundWork = function() {
    return this.data;
};

(上面的写法,我认为是没有加入语法糖的写法,看起来要理解一番)

var a = new TestClass("a");
var b = new TestClass("b");

alert(a.boundWork()); // a
alert(b.boundWork()); // b

alert(a.unboundWork()); // a
alert(b.unboundWork()); // b

alert(a.boundWork.call(b)); // a
alert(a.boundWork.call(undefined)); // a

alert(a.unboundWork.call(b)); // b

或更有趣的写法:

var method = a.unboundWork;
method() // undefined. ACK!

再来对比:

method = a.boundWork;
method() // a. TADA MAGIC!

注意看boundWork的执行一直是服从于在它所属的实例,不管你把this改成了什么对象,并用call和apply方法怎么调用。在ActionScript里,这种方式就解释了为什么类里的方法是绑定于它的实例。所以不管这两个方法在哪用,他们始终指向的都是他们所对应的实例(这和actionScript里的事件模型有点类似)。一旦你理解了,那么这种迂回的解决办法就可以被理解了。(这里作者用到一个很有意思的词work-around

(解释:work-around

中文解釋

雖不能根本解決, 但能避開問題的替代方法。

避免問題或困難而旁道而行達到目的。

權宜之計; 應急之策。

原本是電腦術語, 相對於「Fix」而言. 當一個程式有了問題, 找出問題所在然後直接解決它叫做「Fix」; 當問題始終無法解決, 於是想個方法忽略這個問題並使這個問題不致於影響你要用這程式達到的目的, 這樣的方法就叫 Workaround。

英文解釋

workaround means a manner of bypassing a problem caused by a bug without correcting the bug itself.

workaround is similar to "stopgap solution". If there is a problem, a "workaround" doesn‘t eliminate the problem, but it does bypass the problem.

)

(自己主观理解:)

在某些地方,如果你既想需要在类里声明方法,还想用这个方法做自己的事(改变这个方法所指的对象,就是重写this一样),(有空翻译prototype function用法,用的有点抽象)你可以这样写:

package
{
    import flash.display.Sprite;    
    public class FunctionApplyTest extends Sprite
    {
        public function FunctionApplyTest()
        {
            var objA:MyObj = new MyObj("A");
            var objB:MyObj = new MyObj("B");

            objA.sayName();
            objB.sayName();

            objA.sayName.apply(objB, []); // a
            objA.sayName.call(objB); // a

            objA.pSayName.call(objB) // b <---
        }
    }
}

internal dynamic class MyObj
{
    private var _name:String;
    public function MyObj(name:String)
    {
        _name = name;
    }   
    public function sayName():void
    {
        trace(_name);
    }

    prototype.pSayName = function():void {
        trace(this._name);
    };
}

上面代码里,严重注意sayName和pSayName的区别,sayName一直和实例绑定的,但是pSayName就不同了,它既可被MyObj的实例利用,但又不会与特定的实例绑定。

原文地址:https://www.cnblogs.com/Unknw/p/6540054.html