How to do inheritance with javascript object literals?

Hello, I had a problem with how to do inheritance when declaring prototypes of objects with object literal syntax.

I made two feeds to help you help.

This is my base class, almost all objects are defined this way in my application:

Base = function(param){
    this.init(param);
}
Base.prototype = {
    init: function(param){
        this.param = param;
    },
    calc: function(){
        var result = this.param * 10;
        document.write("Result from calc in Base: " + result + "<br/>");
    },
    calcB: function(){
        var result = this.param * 20;
        document.write("Result from calcB in Base: " + result+ "<br/>");
    }
}

Here's how I manage to extend and override methods in Base:

Extend = function(param){
    this.init(param);
}
Extend.prototype = new Base();

Extend.prototype.calc = function(){
    var result = this.param * 50;
    document.write("Result from calc in Extend: " + result+ "<br/>");
}

But I wanted to use the same style as the rest of the application, so I started playing with object literals, but it makes me happily cheer on eclipse and firebug with my meaningless answer to my syntax.

, ? ( , , , .)

Extend = function(param){
    this.init(param);
}
Extend.prototype = {
    : new Base(),
    calc: function(){
        var result = this.param * 50;
        document.write("Result from calc in Extend: " + result+ "<br/>");
    }
}
+5
2

Object.make. Live Example

Extend = function(param){
    this.init(param);
}
Extend.prototype = Object.make(Base.prototype, {
    constructor: Extend,
    calc: function(){
        var result = this.param * 50;
        document.write("Result from calc in Extend: " + result+ "<br/>");
    }
});

, Object.make, ES5, ,

Object.make = function make (proto) {
    var o = Object.create(proto);
    var args = [].slice.call(arguments, 1);
    args.forEach(function (obj) {
        Object.getOwnPropertyNames(obj).forEach(function (key) {
            o[key] = obj[key];
        });
    });
    return o;
}
+7

, .

function extend(original, extension) {
  for (var key in extension) {
    if (extension.hasOwnProperty(key)) {
      original[key] = extension[key];
    }
  }
};

var A = function () {};
var B = function () {};
B.prototype = new A();
extend(B.prototype, {
   methodName: function () {}
});
0

All Articles