【发布时间】: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