简体   繁体   中英

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.

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

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

You need to extend the original prototype rather than assigning a new object as the prototype.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM