Simon Davies
Simon Davies

Reputation: 3686

Javascript: Extending a class

I am testing this at the moment and would like to create a class B that extends class A but having issues with it at present:

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);}
  });

Hoep the two examples makes it easy and hopefully I am doing it right in the first instance. Thanks

Upvotes: 1

Views: 461

Answers (1)

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

Your first example looks fine.

The second example would only work if Function.prototype has been given a function property extend, otherwise it will throw a TypeError.

Try something like this instead.

  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);};

Or, if you want more syntactic sugar, you can create a convenience function to copy the prototype and merge an object into it, with a calling syntax like the extend you're using. I wouldn't necessarily recommend attaching it to Function.prototype though, as there's a good chance it could collide with some third-party code.


Older browsers don't support Object.create. If you need to support legacy browsers, you can write a function like this to emulate it:

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

See here for a look at how this evolved.

Upvotes: 1

Related Questions