user310291
user310291

Reputation: 38190

javascript hasOwnProperty returns true instead of false?

I don't understand why alert(John.hasOwnProperty('firstName')); returns true whereas firstName is defined in Person prototype not in instance John ?

https://jsfiddle.net/xfdnsg2w/

  Person = function(firstName, lastName) {

      this.firstName = firstName;
      this.lastName = lastName;

  }

  var John = new Person("John");
  alert(John.hasOwnProperty('toString'));
  alert(John.hasOwnProperty('firstName'));

Upvotes: 1

Views: 88

Answers (1)

Pointy
Pointy

Reputation: 413757

The "firstName" property in your code is not defined in the Person prototype. It's initialized in the constructor as an "own" property.

Even if there were "firstName" and "lastName" properties on the prototype, as soon as you assign values to them in the constructor they'd become "own" properties anyway. Prototype properties are generally used as properties to access, and usually they have functions as values.

Upvotes: 4

Related Questions