javascript hasOwnProperty返回true而不是false?

时间:2016-08-04 16:39:28

标签: javascript

我不明白为什么警惕(John.hasOwnProperty(' firstName'));返回true而firstName是在Person原型中定义的,而不是在实例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'));

1 个答案:

答案 0 :(得分:4)

" firstName"您的代码中的属性在Person原型中定义为。它在构造函数中初始化为" own"属性。

即使有" firstName"和" lastName"原型上的属性,只要你在构造函数中为它们赋值,它们就会成为自己的"物业无论如何。原型属性通常用作访问属性,通常它们具有值作为函数。