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]];
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
"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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With