The stumbling point here is that Javascript uses prototypal inheritance. What you're seeing there isn't actually inheritance at all.
hasOwnProperty
will return false
if the property:
- Does not exist.
- Exists but only on the prototype chain.
The 'class' in your code is nothing to do with inheritance at all, it's just a function which sets some properties on an object.
That object happens to be an instance of a new empty object, because you called the function with the new
keyword, which is probably where the confusion is coming from.
Imagine rewriting the function as this:
function foo() {
var bar = {};
bar.propname = 'test';
return bar;
}
var baz = foo();
Would you expect baz.hasOwnProperty('propname')
to return true? Absolutely, because we explicitly defined the property on the object.
The alternative way to declare the property would have been to declare it on Foo
's prototype.
function Foo() {
this.bar = 'baz';
}
Foo.prototype.propname = 'test';
var baz = new Foo();
baz.propname; // 'test'
baz.hasOwnProperty('propname'); // false
Again, the magical stuff happening here is all down to the new
keyword. When you call a function with new
the function assigns the value of this
to be a new object and sets the prototype of that object to be the same as the prototype of the function you are calling.
Maybe the easiest way of explaining this is that there is a hasOwnProperty
method on bar
, but if you call bar.hasOwnProperty('hasOwnProperty')
it will return false
.
This is because the hasOwnProperty
method lives at the very top of the prototype chain, on Object.prototype
. Every object in Javascript inherits from here, which is why every object will have a hasOwnProperty
method.
There's a good article on why new
makes object oriented programming difficult in Javascript.