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
Your first example looks fine.
The second example would only work if
Function.prototypehas been given a function propertyextend, otherwise it will throw aTypeError.Try something like this instead.
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
extendyou’re using. I wouldn’t necessarily recommend attaching it toFunction.prototypethough, 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:See here for a look at how this evolved.