2

I have a question about object inheritance with Object.create.

I have two objects, that should behave like interfaces. Object3D and Light. Object3D presents real object in 3D space. It has its position in space and it should have some functions to for example change this position. Light is everything that glows. And every light has its color.

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

Now, I want to have two another objects, which will be 'classes'. First one is AmbientLight. AmbientLight doesnt have position, because it just glows everywhere. So it inherits from Light. The other one is PointLight. PointLight is Light, but it has also position, because it doesn't glow everywhere. It has some range. So it should inherit also from Object3D. How can I do it? Can I merge results from 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;
})();
Entity Black
  • 3,401
  • 2
  • 23
  • 38

1 Answers1

0

You've got exactly the right idea. Simply merge your two objects together where you're setting the prototype:

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

Of course, you have all your normal ugly issues that you get when dealing with multiple inheritance - namely, if you have any member with a common name in both objects, the Object3D member will overwrite the Light member.

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76