我的理解是,Object.hasOwnProperty
方法檢查對象是否具有它自己的屬性名稱,即非繼承屬性。這意味着,只要屬性a就應該返回false。 b。不存在或b。如果它被繼承,則爲。JavaScript:爲什麼Object.hasOwnProperty方法的行爲如此?
如果我錯了,請糾正我,但除非這不使用經典繼承,否則bar
在下面的代碼中繼承自Foo
?爲什麼當propname
屬性是繼承的屬性時hasOwnProperty
方法返回true?我在這裏弄錯了什麼?
另外,如何使用Foo
對象上的hasOwnProperty
?在檢查Foo
對象時,此處的代碼返回false
。
function Foo() {
this.propname = 'test';
}
var bar = new Foo();
console.log(bar.hasOwnProperty('propname')); // returns true
console.log(Foo.hasOwnProperty('propname')); // returns false
的這條線2 ===欄上,沒有原型屬性這裏設置。通過設置Foo.prototype.propname = ...添加原型。# – Douglas
Bar是Foo的一個實例,而不是後代。 – joews
@Douglas請你詳細說明一下嗎?爲什麼這需要原型呢?該方法正在檢查屬性... – shmuli