Object的hasOwnProperty()方法返回一個布爾值,判斷對象是否包含特定的自身(非繼承)屬性。
判斷自身屬性是否存在
1
2
3
4
5
6
7
8
9
10
11
|
var o = new Object(); o.prop = 'exists' ; function changeO() { o.newprop = o.prop; delete o.prop; } o.hasOwnProperty( 'prop' ); // true changeO(); o.hasOwnProperty( 'prop' ); // false |
判斷自身屬性與繼承屬性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
function foo() { this .name = 'foo' this .sayHi = function () { console.log( 'Say Hi' ) } } foo.prototype.sayGoodBy = function () { console.log( 'Say Good By' ) } let myPro = new foo() console.log(myPro.name) // foo console.log(myPro.hasOwnProperty( 'name' )) // true console.log(myPro.hasOwnProperty( 'toString' )) // false console.log(myPro.hasOwnProperty( 'hasOwnProperty' )) // fasle console.log(myPro.hasOwnProperty( 'sayHi' )) // true console.log(myPro.hasOwnProperty( 'sayGoodBy' )) // false console.log( 'sayGoodBy' in myPro) // true |
遍歷一個對象的所有自身屬性
在看開源項目的過程中,經常會看到類似如下的源碼。for...in循環對象的所有枚舉屬性,然后再使用hasOwnProperty()方法來忽略繼承屬性。
1
2
3
4
5
6
7
8
9
10
11
12
|
var buz = { fog: 'stack' }; for ( var name in buz) { if (buz.hasOwnProperty(name)) { alert( "this is fog (" + name + ") for sure. Value: " + buz[name]); } else { alert(name); // toString or something else } } |
注意 hasOwnProperty 作為屬性名
JavaScript 并沒有保護 hasOwnProperty 屬性名,因此,可能存在于一個包含此屬性名的對象,有必要使用一個可擴展的hasOwnProperty方法來獲取正確的結果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
var foo = { hasOwnProperty: function () { return false ; }, bar: 'Here be dragons' }; foo.hasOwnProperty( 'bar' ); // 始終返回 false // 如果擔心這種情況,可以直接使用原型鏈上真正的 hasOwnProperty 方法 // 使用另一個對象的`hasOwnProperty` 并且call ({}).hasOwnProperty.call(foo, 'bar' ); // true // 也可以使用 Object 原型上的 hasOwnProperty 屬性 Object.prototype.hasOwnProperty.call(foo, 'bar' ); // true |
到此這篇關于js屬性對象的hasOwnProperty方法的使用的文章就介紹到這了,更多相關js hasOwnProperty內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/weiqinl/p/8683207.html