【发布时间】:2015-10-20 05:41:48
【问题描述】:
我正在研究 John Resig 的 OOO implementations in 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的目的。我发现这篇文章有一些解释,但我看不懂:Understanding John Resig's 'Simple JavaScript Inheritance'
谁能详细解释它的目的?比如说,给出一些没有initializing的代码失败的场景?
更新
问题解决了。
我写了一篇文章记录下细节:Understanding John Resig’s ‘Simple JavaScript Inheritance’
【问题讨论】:
标签: javascript oop inheritance prototypal-inheritance