gpt4 book ai didi

Javascript 类继承,带有 this._super 和正确的 DefineProperty 描述符

转载 作者:行者123 更新时间:2023-12-03 11:57:09 29 4
gpt4 key购买 nike

我真的很喜欢John Resig's simple inheritance method 。它有很好的语法,而且 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 的内容有点长,请查看 this cool pen I made以获得更清晰的示例。

...// 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

关于Javascript 类继承,带有 this._super 和正确的 DefineProperty 描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25560059/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com