I want to know why the three.js code is structured like this:
THREE.Camera = function(){
THREE.Object3D.call(this);
//add more Camera specific properties and methods
}
THREE.Camera.prototype = new THREE.Object3D();
THREE.Camera.prototype.constructor = THREE.Camera;
THREE.Camera.prototype.//add more camera specific methods...
I want to know why they call the base constructor in the current constructor and also for the prototype?
In MDN they show a pattern like this:
subType = function(){
//new properties for subType
}
subType.prototype = new baseType();
They don’t have the call to the base constructor in the subType constructor, so why does THREE.js do this?
Since each
THREE.Object3Dinstance inherits fromTHREE.Object3D.prototype, by settingTHREE.Camera.prototypethis way, eachTHREE.Camerainstance will also inherit fromTHREE.Object3D.prototype.If you don’t do this,
THREE.Camerainstances won’t inherit any properties assigned toTHREE.Object3D.prototype.So, both parts are important:
By setting
THREE.Camera.prototypeappropriately, new instances will inherit fromTHREE.Object3D.prototypeand these properties are shared by all instances.By calling the “parent” constructor function you are initializing each instance with instance-specific data.
That said, setting the prototype like this is not the best approach. What if
THREE.Object3Dexpects arguments without which the constructor would not work?A better approach is to create an empty object which inherits from
THREE.Object3D.prototype, since this is all you need:Reference:
Object.create