Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do inheritance with JavaScript object literals?

Hello I have a problem with how to do inheritance while declaring object prototypes with object literal syntax.

I have made two Fiddles to help you help me.

  • Fiddle1, This one works
  • Fiddle2, This one doesn't work

This is my base class, almost all objects is defined in 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/>");
    }
}

This is how I succeed extending and overriding 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 around with object literals but it is driving me nuts eagerly cheered on by eclipse and firebug with its nonsense response to my syntax.

Now on to the question of how do I convert my succeeded extension code to object literal style? Here is one of many attempts (it don't compile but will give you an rough idea how I want the code to look like.)

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/>");
    }
}
like image 724
Farmor Avatar asked Nov 18 '11 11:11

Farmor


1 Answers

You want 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/>");
    }
});

If you want an ES5 compliant implementation of Object.make to just plug into your code then use

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;
}
like image 164
Raynos Avatar answered Sep 24 '22 20:09

Raynos