具有this._super和正确的defineProperty描述符的Javascript类继承

时间:2014-08-29 00:41:59

标签: javascript oop inheritance getter-setter prototypal-inheritance

我真的跟John Resig's simple inheritance method交往。它有很好的语法,而且this._super非常强大。

2014年很难,我希望能够定义getter& amp; setters以及其他描述符(但如果可能的话仍然保持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();
     }
  }
});

1 个答案:

答案 0 :(得分:1)

我不知道你为什么要这样做,因为你可以通过JavaScript对象的性质轻易地绕过这个,但我喜欢你问题的精神。

我没有在你的类中定义方法,而是想到为什么不为所有类定义它?在eJohn的代码中,我在将原型声明为变量之后立即添加了两个函数。 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