简体   繁体   English

javascript hasOwnProperty返回true而不是false?

[英]javascript hasOwnProperty returns true instead of false?

I don't understand why alert(John.hasOwnProperty('firstName')); 我不明白为什么警报(John.hasOwnProperty('firstName')); returns true whereas firstName is defined in Person prototype not in instance John ? 返回true,而firstName是在Person原型中定义的,而不是在John实例中定义的?

https://jsfiddle.net/xfdnsg2w/ 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. 它在构造函数中初始化为“ own”属性。

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. 即使原型上具有“ firstName”和“ lastName”属性,只要在构造函数中为它们分配值,它们也将立即成为“所有者”属性。 Prototype properties are generally used as properties to access, and usually they have functions as values. 原型属性通常用作访问的属性,并且通常具有作为值的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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