如何使用JavaScript对象文字进行继承?

Far*_*mor 5 javascript oop inheritance

您好我在使用对象文字语法声明对象原型时如何进行继承有问题.

我制作了两个小提琴来帮助你.

这是我的基类,几乎所有对象都是以这种方式在我的应用程序中定义的:

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/>");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在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/>");
}
Run Code Online (Sandbox Code Playgroud)

但是我想使用与应用程序其余部分相同的样式,所以我开始玩对象文字但是它让我疯狂地对eclipse和firebug以及对我的语法的无意义响应感到高兴.

现在讨论如何将成功的扩展代码转换为对象文字样式的问题?这是许多尝试之一(它不编译但会让你大致了解我希望代码看起来像.)

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/>");
    }
}
Run Code Online (Sandbox Code Playgroud)

Ray*_*nos 7

你想要的Object.make.实例

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/>");
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您希望ES5兼容的实现Object.make只是插入您的代码,那么使用

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;
}
Run Code Online (Sandbox Code Playgroud)