Because you trying to access prototype wrong way, it should be g.__proto__
(but you should never use g.__proto__
, it's deprecated and does not work on all objects) or Object.getPrototypeOf(g)
:
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
}
};
var g = new Graph();
console.log(g.__proto__); // get access to prototype
console.log(Object.getPrototypeOf(g)); // get access to prototype
UPDATE
"I would like to execute something live new Graph(3), and expect the vertices to have 3 in the array."
Just use g.addVertex(3);
to invoke addVertex
function with parameter 3
(it will change only g.vertices
array). Here is the example:
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
}
};
var g = new Graph();
g.addVertex(3);
console.log(g.vertices);
But you can pass parameter to constructor as well, like this:
function Graph(param) {
this.vertices = [param];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
}
};
var g = new Graph(1);
var h = new Graph(2);
console.log(g.vertices);
console.log(h.vertices);