Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why object.[[Prototype]] does not work in Chrome Developer Tools?

I'm trying to do call the [[Prototype]] method of an object, by using this tutorial, from Mozilla (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain), but it does not seem to work.

Does anyone knows why?

Thanks,

Some code:

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

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

var g = new Graph();
g.[[Prototype]];
like image 820
Johann Gomes Avatar asked Sep 18 '26 23:09

Johann Gomes


1 Answers

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);
like image 138
Commercial Suicide Avatar answered Sep 20 '26 11:09

Commercial Suicide