JavaScript扩展对象和原型

时间:2014-01-12 00:55:58

标签: javascript inheritance prototype

我正在创建一个框架来简化面向对象编码的原型。但我正在思考JavaScript中的继承。

默认情况下,为了扩展对象,我们写:

var B = function() { /*...*/ } ;
B.prototype = new A() ;

A 构造函数需要参数吗?

var A = function(args) {
    if (!args) throw "Arguments required." ;
} ;

或者 构造函数也可以在 B 实例化之前执行不需要的操作。

您建议更换默认继承行为? (我考虑过将所有“类”的所有成员存储起来,以便在继承或混合时进行复制。)

2 个答案:

答案 0 :(得分:3)

如果你想在不调用构造函数的情况下从原型继承,你可以使用Object.create()做这样的事情:

var B = function() { /*...*/ };

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

在上文中,Object.create(A.prototype)将返回一个新对象,其原型由A.prototype提供,并且在不调用A()的情况下执行此操作。第二行是那里你可以在B的任何实例上查找构造函数属性,它将指向B()

需要注意的一点是Object.create()相对较新,因此您可能需要为旧版浏览器添加填充功能。你可以在这里找到一个,以及更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

答案 1 :(得分:1)

我通常使用defclass实用程序函数在JavaScript中定义“类”:

function defclass(base, body) {
    var uber = base.prototype;
    var prototype = Object.create(uber);
    var constructor = (body.call(prototype, uber), prototype.constructor);
    constructor.prototype = prototype;
    return constructor;
}

然后我按如下方式使用它:

var A = defclass(Object, function () {
    this.constructor: function (arg1, arg2) {
        this.arg1 = arg1;
        this.arg2 = arg2;
    }

    this.log = function (which) {
        console.log(which ? this.arg1 : this.arg2);
    };
});

继承很简​​单:

var B = defclass(A, function (uber) {
    this.constructor = function (arg1, arg2, arg3) {
        uber.constructor.call(this, arg1, arg2);
        this.arg3 = arg3;
    };

    this.log = function (which) {
        uber.log.call(this, which);
        console.log(this.arg3);
    };
});

正如您在我们扩展“课程”时所看到的,我们使用Object.create。这是一种新的继承方式。使用new已过时。在B的构造函数中,我们使用A将参数传递给uber.constructor.call的构造函数。

如果你喜欢这种模式,那么你应该看一下augment库。

相关问题