Javascript:扩展一个类

时间:2012-02-20 22:00:01

标签: javascript class javascript-framework

我现在正在测试这个,并希望创建一个扩展A类的B类,但目前存在问题:

CLASS A

  var CustomClassA = function(){
    console.log('Custom Class A loaded')
    this.message = ' Method Called';

  }

  CustomClassA.prototype    =   {
    constructor : CustomClassA,
    firstMethod : function(msg){
        this._output(msg);
    },
    secondMethod : function(msg){
        this._output(msg);
    },
    thirdMethod: function(msg){
        this._output(msg);
    },
    _output: function(m){
        return console.log(m + this.message);
    }   
  }

CLASS B:

  var CustomClassB =  CustomClassA.extend(

    function CustomClassB(){
        console.log('Custom Class B loaded')
            this.message = ' Method Called from class B';

    },{
        firstMethod : function(msg){this._output(msg);},
            secondMethod : function(msg){this._output(msg);},
        thirdMethod: function(msg){this._output(msg);},
        _output: function(m){return console.log(m + this.message);}
  });

这两个例子让我很容易,希望我在第一个例子中做得很好。 谢谢

1 个答案:

答案 0 :(得分:1)

你的第一个例子看起来不错。

第二个示例仅在Function.prototype被赋予函数属性extend时才有效,否则将抛出TypeError

尝试这样的事情。

  function CustomClassB(){
      console.log('Custom Class B loaded');
      this.message = ' Method Called from class B';
  }

  CustomClassB.prototype = Object.create(CustomClassA.prototype);

  CustomClassB.prototype.firstMethod = function(msg){this._output(msg);};
  CustomClassB.prototype.secondMethod = function(msg){this._output(msg);};
  CustomClassB.prototype.thirdMethod = function(msg){this._output(msg);};
  CustomClassB.prototype._output = function(m){return console.log(m + this.message);};

或者,如果你想要更多的语法糖,你可以创建一个便利函数来复制原型并将一个对象合并到它中,使用你正在使用的extend之类的调用语法。我不一定会建议将它附加到Function.prototype,因为它很可能会与某些第三方代码发生冲突。


较旧的浏览器不支持Object.create。如果您需要支持旧版浏览器,可以编写这样的函数来模拟它:

function objectCreate(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

请参阅here了解这是如何演变的。