0

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.

  • 2
    Because it's an inherited, not an own property. That's what prototypes are all about. – Bergi May 18 '14 at 09:56
  • No, you're not doing [correct javascript inheritance](http://stackoverflow.com/q/10898786/1048572). See also [what's wrong about the use of `new` here](http://stackoverflow.com/q/12592913/1048572) – Bergi May 18 '14 at 09:59

4 Answers4

1

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

Oleg
  • 9,341
  • 2
  • 43
  • 58
1

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.

gp.
  • 8,074
  • 3
  • 38
  • 39
0

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

tusharmath
  • 10,622
  • 12
  • 56
  • 83
0

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.