简体   繁体   中英

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'));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM