2
我有這樣一段代碼(從「JavaScript的忍者的祕密」):的JavaScript子類代碼的解釋
(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
(這更有意義?),它似乎工作正常。
我認爲你的問題只是回答了我的問題[鏈接](http://stackoverflow.com/questions/20733249/ruby-code-blocks-versus-javascript-anonymous-functions-distiction) – ialexander