继承自2个对象

时间:2013-09-25 15:24:45

标签: javascript

我对Object.create有一个关于对象继承的问题。

我有两个对象,应该像接口一样。 Object3DLightObject3D在3D空间中呈现真实对象。它有它在太空中的位置,它应该有一些功能,例如改变这个位置。 Light是发光的一切。每一盏灯都有它的颜色。

// I have resons to use iif, dont bother with that ;) 

var Object3D = (function() {

    var Object3D = function() {
        this.position = vec3.create();
    };

    return Object3D;
})();


var Light = (function() {

    var Light = function() {
        this.color = new Array(4);
    };

    return Light;
})();

现在,我想要另外两个对象,它们将是“类”。第一个是AmbientLightAmbientLight没有位置,因为它随处可见。所以它继承自Light。另一个是PointLightPointLightLight,但它也有位置,因为它不会随处发光。它有一定的范围。所以它也应该从Object3D继承。我该怎么做?我可以合并Object.create的结果吗?

var AmbientLight = (function() {

    var AmbientLight = function() {
        Light.call(this);
    };

    AmbientLight.prototype = Object.create(Light.prototype);

    return AmbientLight;
})();


var PointLight = (function() {

    var PointLight = function() {
        Light.call(this);
        Object3D.call(this);
        this.range = 10.0;
    };

    // this isnt correct
    // how to make it correct? 
    PointLight.prototype = Object.create(Light.prototype);
    PointLight.prototype = Object.create(Object3D.prototype); 

    return PointLight;
})();

1 个答案:

答案 0 :(得分:0)

你有完全正确的想法。只需将两个对象合并到您设置原型的位置:

PointLight.prototype = Object.create(Light.prototype);
var obj3D = Object.create(Object3D.prototype);

for (var key in obj3D) {
    if (obj3D.hasOwnProperty(key)) {
        PointLight.prototype.key = obj3D.key;
    }
}

当然,您在处理多重继承时遇到了所有正常的丑陋问题 - 即,如果您在两个对象中都有任何具有公用名的成员,Object3D成员将覆盖{{1成员。

相关问题