我正在学习约翰·雷西格的OOO在JavaScript中的实现。守则是这样的:
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
this.Class = function(){};
Class.extend = function(prop) {
var _super = this.prototype;
initializing = true;
var prototype = new this();
initializing = false;
for (var name in prop) {
// ...
}
function Class() {
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.extend = arguments.callee;
return Class;
};
})();问题是:为什么我们在这里使用initializing ?
我猜var prototype = new this();语句可能是异步的。因此,当调用new ChildClass()时,可能还没有完成初始化(将properties分配给ChildClass原型)。但我不太确定它是否正确。
在搜索之后,我仍然无法理解使用变量initializing的目的。我发现这篇文章有一些解释,但我无法理解:理解John的“简单JavaScript继承”
有人能详细解释一下它的目的吗?比方说,给出一些没有initializing代码就会失败的场景
更新
问题解决了。
我写了一篇文章来记录细节:理解John的“简单JavaScript继承”
发布于 2015-10-20 05:56:01
function Class() {
if ( !initializing && this.init )
this.init.apply(this, arguments);
}当initializing为真时,您将“设置”类对象本身,因此不希望调用每个具体类定义的init实例方法。
您可以这样做: var RedCoupe = Class.extend({ init: this._type = 'coupe';this._color = 'red';});var myCar =新的RedCoupe ();
在这种情况下,您希望new RedCoupe();调用init,但不想在违背var RedCoupe = Class.extend({ ... });时调用init,这样做有意义吗?
https://stackoverflow.com/questions/33228841
复制相似问题