0

Suppose I have this code:

function Graph() {
  this.vertices = [];
  this.edges = [];
}

Graph.prototype = {
  addVertex: function(v){
    this.vertices.push(v);
  }
};

Is it possible to add the addVertex property name inside function Graph() and thus eliminate the second part of this code altogether (from where Graph.prototype = begins)? I've tried this but it doesn't work:

function Graph() {
  this.vertices = [];
  this.edges = [];
  addVertex = function(v){
    this.vertices.push(v);
  };
}
daremkd
  • 8,244
  • 6
  • 40
  • 66
  • 2
    It would be `this.addVertex = function...` – James Thorpe Oct 30 '15 at 13:23
  • Gauvar Sacnchan's answer is correct but if you wan't to attach the function to the prototype of the object you should change this.addVertex with Graph.prototype.addVertex – memo Oct 30 '15 at 14:03

1 Answers1

0

Yes, you can do this in the following manner:

function Graph() {
  this.vertices = [];
  this.edges = [];
  this.addVertex = function(v){
    this.vertices.push(v);
  }; 
 return this;
}
Wes Foster
  • 8,770
  • 5
  • 42
  • 62
Gaurav Sachan
  • 320
  • 1
  • 10