Javascript继承问题

时间:2017-12-17 09:00:31

标签: javascript inheritance prototypal-inheritance

我试图围绕原型继承。 我已经阅读了关于它的MDN文档,但它并没有让我更聪明。到目前为止,我有以下代码......

var Vertex = function(id, options){
  this.options = options || {};
  this.id = id;

  this.position = new THREE.Vector3(0, 0, 0);
  this.velocity = new THREE.Vector3(0, 0, 0);
  this.acceleration = new THREE.Vector3(0, 0, 0);

  this.toString = function(){
    return this.id.toString();
  };

  this.edge_count = 0;
  this.edges = {};

  if(!this.options.hasOwnProperty('label')){
    this.options.label = {
      text: '',
      direction: 'x',
      distance: '10'
    };
  };
};

...我想从中继承"继承"构造函数添加的所有属性。 Vertex有一个绘制方法,可以将网格添加为顶点object。所以我写了......

var CameraVertex = function(id, camera){
    Vertex.call(this);
    this.object = camera;
    this.id = id;
};
CameraVertex.prototype = Object.create(Vertex.prototype);
CameraVertex.prototype.constructor = CameraVertex;

...所以我能够使用CameraVertex作为Vertex的替代品(除了构造函数,它只是将相机分配给Vertex的对象属性,它通常包含一个Mesh或小组。

但由于某些原因,当我在CameraVertex和常规顶点之间创建边时,似乎没有source.object

点击谷歌登录并用鼠标选择顶点后,可以在Social Cartography找到完整的示例。

1 个答案:

答案 0 :(得分:1)

当你调用继承的Object的构造函数时,你还需要传递所有必要的参数。

var CameraVertex = function(id, camera, options){
    Vertex.call(this, id, options);
    this.object = camera;
    this.id = id;
};

即使我不熟悉THREE,所以我不理解你的source.object问题,到目前为止,我可以看到这个问题。