[英]Javascript class inheritance w/ both this._super and proper defineProperty descriptors
我真的很討厭John Resig的簡單繼承方法 。 它具有不錯的語法,this._super非常強大。
2014年艱難,我希望能夠定義getter和setter以及其他描述符(但如果可能的話,仍要保持Resig版本的簡單性)。
在保持類似於我所珍視的Resig的語法的同時,我將如何處理?
我的夢想是這樣的:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
tools: { // <---- this would be so awesome
get: function() { ... },
set: function(v) { ... },
enumerable: true
},
});
var Ninja = Person.extend({
init: function(){
this._super( false );
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return true;
},
tools: {
get: _super, // <---- and this too
set: function(v) {
this._super(v);
doSomethingElse();
}
}
});
我不知道您為什么要這樣做,因為您可以通過JavaScript對象的性質輕松地繞開它,但是我喜歡您提出問題的精髓。
而不是在您的類中定義方法,我想到了為什么不為所有類都定義它? 在eJohn的代碼中,我在將prototype聲明為變量之后立即添加了兩個函數。 StackOverflow有點長,所以請查看我制作的這款炫酷筆,以獲得更清晰的示例。
...// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
prototype.set = function (attr, val) {
return this[attr] = val;
}
prototype.get = function (attr) {
return this[attr];
}
// Copy the properties over onto the new prototype ...
然后您的類將如下所示:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
});
var Ninja = Person.extend({
init: function(){
this._super( false );
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return true;
},
set: function (attr, val) {
this._super(attr, val);
console.log('doing other things');
}
});
因此,您可以執行以下操作:
var p = new Person(true);
p.get('dancing'); // => true
p.set('dancing', false); // Telling the person to please stop dancing (he's drunk)
p.dance(); // => false... "whew!"
p.get('dancing') // => false - he must be asleep
var n = new Ninja();
n.get('dancing'); // => false, ninjas don't dance
n.set('dancing', true); // except my ninjas do
n.get('dancing'); // => true, cause they're rad
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.