6

我想知道为什么three.js代码的结构是这样的:

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...

我想知道他们为什么在当前构造函数和原型中调用基本构造函数?

在 MDN 中,他们展示了这样的模式:

subType = function(){
    //new properties for subType
}

subType.prototype = new baseType();

他们没有在 subType 构造函数中调用基本构造函数,那么为什么 THREE.js 会这样做呢?

4

1 回答 1

7

Since each THREE.Object3D instance inherits from THREE.Object3D.prototype, by setting THREE.Camera.prototype this way, each THREE.Camera instance will also inherit from THREE.Object3D.prototype.

If you don't do this, THREE.Camera instances won't inherit any properties assigned to THREE.Object3D.prototype.

So, both parts are important:

  • By setting THREE.Camera.prototype appropriately, new instances will inherit from THREE.Object3D.prototype and 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.Object3D expects 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:

THREE.Camera.prototype = Object.create(THREE.Object3D.prototype);
THREE.Camera.prototype.constructor = THREE.Camera;

Reference: Object.create

于 2012-06-19T12:59:10.183 回答