Does it make sense to use .apply( ) and pass the same instance as context?

ぐ巨炮叔叔 提交于 2019-12-02 05:36:27

问题


I'm reading Javascript Web Applications, from O'Reilly. At various points in the book, the author uses something along the following:

instance.init.apply(instance, arguments);

Does this make any sense? Isn't this exactly the same as:

instance.init(arguments);

.call() and .apply() are used to manually set the execution context of a function. Why should I use them when I'm intending to use the original execution context anyway?


回答1:


The point is that arguments is an array-like object. Doing ...

instance.init(arguments);

... passes one argument, which is an array-like object containing certain arguments. On the other hand, doing ...

instance.init.apply(instance, arguments);

... will pass the array-like object as separate arguments. It is true that setting instance is kind of useless because you already wrote it, but if using .apply you simply need to set the this value as well.

A quick example of the difference:

function log(a, b, c) {
    console.log(a, b, c);
}

function log2() {
    log.apply(null, arguments); // `this` value is not meaningful here,
                                // it's about `arguments`
}

function log3() {
    log(arguments);
}

log(1, 2, 3);  // logs:  1, 2, 3

log2(1, 2, 3); // logs:  1, 2, 3

log3(1, 2, 3); // logs:  <Arguments>, undefined, undefined
               //        where <Arguments> contains the values 1, 2, 3



回答2:


Using apply() in that example insures that 'this' === instance, instead of DOMWindow if instance.init() is executed from another function/expression.

var x = function(){ debugger; },
    y = function(){ x.apply(x, arguments); },
    z = function() { x(arguments); };

y("abc", true, []); // this === x
z("abc", true, []); // this === DOMWindow

It's simply specifying context.



来源:https://stackoverflow.com/questions/8315744/does-it-make-sense-to-use-apply-and-pass-the-same-instance-as-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!