TheHumbleGhost
TheHumbleGhost

Reputation: 49

How does hasOwnProperty work on properties inherited from the prototype?

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.

Upvotes: 0

Views: 80

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55613

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.

Upvotes: 1

Timur
Timur

Reputation: 46

why does g.hasOwnProperty('addVertex') yields false

That is the way hasOwnProperty works. From MDN:

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.

So hasOwnPropertydoes not traverse the prototype chain when do its checks.

You can use in operator to check property in prototype chain.

Upvotes: 2

Related Questions