Search code examples
javascriptinheritanceprototypal-inheritance

Javascript Inheritance Woes


I'm trying to wrap my head around prototypal inheritance. I've read the MDN documentation on it, but it didn't leave me much smarter. I have the following code so far...

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

... from which I want to "inherit" all the properties added by the constructor. Vertex has a paint method that adds a Mesh as the Vertex's object. So I wrote...

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

... so I'd be able to use CameraVertex as a drop in replacement for Vertex (except the constructor, which simply assigns the camera to the Vertex's object property, which would usually hold a Mesh or a Group.

But for some reason, there seems to be no source.object when I create an edge between the CameraVertex and a regular vertex.

The complete example can be found at Social Cartography after clicking signin with google and selecting the vertex with your mouse.


Solution

  • When you call the constructor of the inherited Object you need to pass also all necessary parameters.

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

    Even though I'm not familiar with THREE so I don't understand your problem with source.object, so far I can see this problem.