Mohammed Imran Khan
Mohammed Imran Khan

Reputation: 179

Define a prototype using new operator in JavaScript

I was exploring prototype in JavaScript.

function A () { this.x = 7; };
function B () {};
B.prototype = new A();
var b = new B();
b.x; // => 7
// But why is it giving 'false' below
b.hasOwnProperty('x'); // => false

My Query is,
is it correct code?
If 'b' is has a value for 'x' , then it should be its property. If so, why is it giving false.
Please clarify.

Upvotes: 0

Views: 50

Answers (4)

gp.
gp.

Reputation: 8225

x is a property on B.prototype and not on object b. B.prototype gets stored on b.proto and not on b itself.

Regarding your code, you should additionally do this:

function B(){ A.apply(this, arguments); }

This would make sure the base constructor is invoked whenever B() constructor is invoked to create an instance. This would also make the property "x" available on every instance of B.

Upvotes: 1

Mohammed Imran Khan
Mohammed Imran Khan

Reputation: 179

Thanks gp & all:

function B () { A.call(this); };
B.prototype = Object.create(A.prototype);
var b = new B();
b.hasOwnProperty('x'); // => true

The above code is adding 'x' to b.

Upvotes: 0

tusharmath
tusharmath

Reputation: 10992

the value of x is stored in b.__proto__.x and not b.x that's why the hasOwnProperty method returns false.

Upvotes: 0

Oleg
Oleg

Reputation: 9359

b.x is a property on the prototype of b, not on b itself. hasOwnProperty only checks for own properties, hence the name.

Upvotes: 1

Related Questions