I have been reading through Mozilla Developer Network lately on JavaScript inheritance model. I am highly confused on one point. Here's the code from MDN:
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
}
};
var g = new Graph();
console.log(g.hasOwnProperty('vertices'));// true
console.log(g.hasOwnProperty('addVertex'));// false
console.log(g.__proto__.hasOwnProperty('addVertex'));// true
What I don't understand is that why does g.hasOwnProperty('addVertex')
yields false since addVertex
is a property of g
although it's defined in Graph's prototype but still it is part of Graph
.
Because hasOwnProperty
specifically says it return false on inherited
properties
MDN:
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.
As for your second question - it depends on exactly how you have an object inherit from Graph
. In the ES5 way, I would do this:
var InheritedFromGraph = function() {
Graph.call(this);
}
InheritedFromGraph.prototype = Graph.prototype;
and then, yes, InheritedGraph
will get the properties verticies
and edge
that Graph
defined in it's constructor.