【发布时间】:2014-01-11 01:21:24
【问题描述】:
我有这段代码(来自“Javascript Ninja 的秘密”):
(function() {
var initializing = false,
superPattern = /xyz/.test(function() { xyz; }) ? /\b_super\b/ : /.*/;
Object.subClass = function(properties) {
var _super = this.prototype;
initializing = true;
var proto = new this();
initializing = false;
for (var name in properties) {
proto[name] = typeof properties[name] == "function" &&
typeof _super[name] == "function" &&
superPattern.test(properties[name]) ?
(function(name, fn) {
return function() {
var tmp = this._super;
this._super = _super[name];
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, properties[name])
:
properties[name];
}
function Class() {
if (!initializing && this.init) {
this.init.apply(this, arguments);
}
}
Class.prototype = proto;
Class.constructor = Class; // Why do we need this?
Class.subClass = arguments.callee; // Why is this not Object.subClass?
return Class;
};
})();
var Person = Object.subClass({
init: function(isDancing) {
this.dancing = isDancing;
return true;
},
dance: function() {
return this.dancing;
}
});
var person = new Person(true);
alert (person.dance());
我很难理解两件事:
- 为什么是
Class.constructor = Class?
为什么我们需要重写它?我尝试将其注释掉,效果非常好。 - 为什么我们有
Class.subClass = arguments.callee?
我尝试使用Class.subClass = Object.subClass(这更有意义?),它似乎工作正常。
【问题讨论】:
-
我认为你的问题刚刚回答了我的问题link
标签: javascript object constructor