JS的简单继承实现:这是一个很好的例子吗?

时间:2013-02-22 04:56:32

标签: javascript node.js class inheritance

来自Dojo,我真的错过了很多 Dojo的declare()功能。 我正在开发一个复杂的应用程序,我用Node lang.inherits()破解了生活地狱,使其更加......更好,更强大。

这是一个示例,向您展示它的实际作用:

var First = declare( null, {
  one: function(p){ 
    console.log("one in First");
    console.log(p); 
    return 1000; 
  },
  two: function(p){ 
    console.log("two in First");
    console.log(p);
    return 1001; 
  },
  constructor: function(a){ 
    this.a = a; 
    console.log("Constructor of First called");
  },
})

var Second = declare( First, {
  two: function( p ){
    console.log("two in Second"); 
    console.log( p );
    a = this.inherited(arguments);
    console.log("Inherited function returned: " + a );
  },
  constructor: function(a){ 
    console.log("Constructor of Second called, and this.a is...");
    console.log( this.a );
  },
})

console.log("Creating first...");
first = new First(10);
console.log("Creating second...");
second = new Second( 20 );

console.log( "first.a:")
console.log( first.a );
console.log( "second.a:")
console.log( second.a );

console.log( "first.one(1):")
first.one(1);
console.log( "first.two(2):")
first.two(2);

console.log( "second.one(3):")
second.one(3);
console.log( "second.two(4):")
second.two(4);

将显示:

Creating first...
Constructor of First called
Creating second...
Constructor of First called
Constructor of Second called, and this.a is...
20
first.a:
10
second.a:
20
first.one(1):
one in First
1
first.two(2):
two in First
2
second.one(3):
one in First
3
second.two(4):
two in Second
4
two in First
4
Inherited function returned: 1001

我知道函数lang.inherits()是极简主义的原因:nodejs不想在Javascript中强加处理“类”,原型和对象的特定方法。

然而,很多代码都充满了:

function SomeClass( options ){
  this.options = options;
}

SomeClass.prototype.functionOne = function(something){
  //...
}
SomeClass.prototype.functionTwo = function(something){
  //...
}

哪个(并且......好吧,应该?)写成:

SomeClass = declare( null, {
  constructor: function(options){
    this.options = options;
  },
  functionOne: function(something){
    // ...
  },
  functionTwo: function(something){
    // ...
  },
})

能够做到的好处:

SomeOtherClass = declare( SomeClass, {
  constructor: function(){
    this.options['manipulate'] ++;
  },
  functionOne: function(something){
    this.inherited(arguments); // Call the superclass method
    // ...
  },
})

会自动调用父级的构造函数等。 (为了实现this.inherited()我实际上最终创建了函数的哈希映射,因为它们实际上是无名称的;)

这与Dojo的主要区别在于此版本不实现多重继承和mixin。但是,虽然多个继承/ mixin在客户端环境中有意义,但我觉得它们在服务器端程序中会成为一个重大的过度杀伤力。 好的......这是代码。 你能发现这个代码真的有什么问题吗?

我发明了一些已存在的东西吗?

我们走了......

var 
  dummy
;

var declare = exports.declare = function(superCtor, protoMixin) {

  // Kidnap the `constructor` element from protoMixin, as this
  // it mustn't get copied over into the prototype
  var constructor = protoMixin.constructor;
  delete protoMixin.constructor;

  // The function that will work as the effective constructor. This
  // will be returned
  var ctor = function(){

    // Call the superclass constructor automatically
    if( typeof( superCtor.prototype.constructor === 'function' ) ){
       superCtor.prototype.constructor.apply( this, arguments );
    }

    // Call its own constuctor (kidnapped a second ago)
    if( typeof( constructor ) === 'function' ){
      constructor.apply( this, arguments );
    }
  };

  // The superclass can be either an empty one, or the one passed
  // as a parameter
  superCtor = superCtor === null ? function(){} : superCtor;

  // Create the new class' prototype. It's a new object, which happen to
  // have its own prototype (__proto__) set as the superclass' and the
  // `constructor` attribute set as ctor (the one we are about to return)
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });

  // Implement inherited() so that classes can run this.inherited(arguments)
  // This will only work for sub-classes created using declare() as they are
  // the ones with the _inheritMap in their prototype
  protoMixin.inherited = function(args){
    var name, fn;

    // Look for the name in the _inheritMap
    name = this._inheritMap[ args.callee ];
    if( name ){
      fn = superCtor.prototype[name];
      if( fn ){
        return fn.apply( this, args );
      } else {
        throw( new Error("Method " + name + "() not inherited!") );
      }
    }
  }

  // Copy every element in protoMixin into the prototype.
  ctor.prototype._inheritMap = {}
  for( var k in protoMixin ){
    ctor.prototype[ k ] = protoMixin[ k ];
    ctor.prototype._inheritMap[ protoMixin[ k ] ] = k;
  }

  return ctor;
};
exports = module.exports = declare;

2 个答案:

答案 0 :(得分:0)

我会看npm install declarejs,这基本上是Dojo声明的翻录版本。

您可以找到更多信息here

就我个人而言,我更喜欢像Backbone的.extend()这样的东西,很容易被撕掉。

答案 1 :(得分:0)

嗯,我认为答案是“如果有效,那就太好了!”。 它很有效......所以:太棒了!

为了将来参考,“声明”在GitHub上:

https://github.com/mercmobily/JsonRestStores/blob/master/declare.js

我更新了代码,以便this.inherited(arguments)在没有hashmap的情况下工作。

目前,它是:

的一部分

https://github.com/mercmobily/JsonRestStores

即使我不妨创建一个单独的存储库,因为它一个方便的函数,它本身就具有!

Merc的。