【问题标题】:Why is some_func(…) != some_func.call(this, …) in a constructor为什么 some_func(...) != some_func.call(this, ...) 在构造函数中
【发布时间】:2012-07-14 19:01:48
【问题描述】:

我一直认为some_function(...)some_function.call(this, ...) 完全相同。这似乎不适用于构造函数/对象构造上下文中的调用:

function Class(members, parent) {
    function Ctor(value) {
        members.__init__.call(this, value);
        return this;
    };
    Ctor.prototype = members;
    Ctor.prototype.__proto__ = parent.prototype;
    return Ctor;
}

var Base = Class({
    __init__: function(value) {
        this.value = value;
    }
}, {});

var Child = Class({
    __init__: function(value) {
        // Base(value*2); ← WON'T WORK AS EXPECTED
        Base.call(this, value*2); // works just fine
    }
}, Base);

Child.__init__ 中,有必要使用对Base.call(this, value) 的显式调用。如果我不使用这种冗长的表达方式,this 将在被调用的基本构造函数中命名全局对象(浏览器中的window)。使用"use strict" 会抛出错误,因为在严格模式下没有全局对象。

谁能解释一下为什么我必须在这个例子中使用Func.call(this, ...)

(使用 Node.js v0.6.12 和 Opera 12.50 测试。)

【问题讨论】:

    标签: javascript oop constructor


    【解决方案1】:

    使用.call 调用函数与仅使用() 调用函数不同。使用.call,您可以在第一个参数中为调用显式设置this 的值。在正常调用中,this 值将隐含为全局对象或undefined,具体取决于是否启用了严格模式。

    func.call({}, 1); //Call the function func with `this` set to the object and pass 1 as the first argument
    
    func(1); //Call the function func with 1 as the first argument. The value of this inside the function depends on whether strict mode is on or off.
    

    .call


    我一直认为 some_function(...) 与 some_function.call(this, ...)。这似乎不适用于通话 在构造函数/对象构造上下文中:

    这不是真的,它们永远不会相同。您可能会将它与调用函数作为某个对象的属性混淆。 obj.method() 意味着obj 是方法调用的this 的值,它实际上与obj.method.call(obj) 相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      相关资源
      最近更新 更多