JavaScript中Object對象原型上的hasOwnProperty()用來判斷一個屬性是定義在對象本身而不是繼承自原型鏈。
obj.hasOwnProperty(prop)
參數 prop
要檢測的屬性 字符串 名稱或者 Symbol
(ES6)
-
o = new Object();
-
o.prop = 'exists';
-
o.hasOwnProperty('prop'); // 返回 true
-
o.hasOwnProperty('toString'); // 返回 false
-
o.hasOwnProperty('hasOwnProperty'); // 返回 false
使用hasOwnProperty作為某個對象的屬性名
因為javascript沒有將hasOwnProperty作為一個敏感詞,所以我們很有可能將對象的一個屬性命名為hasOwnProperty,這樣一來就無法再使用對象原型的 hasOwnProperty 方法來判斷屬性是否是來自原型鏈。
-
var foo = {
-
hasOwnProperty: function() {
-
return false;
-
},
-
bar: 'Here be dragons'
-
};
-
foo.hasOwnProperty('bar'); // 始終返回 false
不能使用 該對象.hasOwnProperty
這種方法,怎么來解決這個問題呢?我們需要使用原型鏈上真正的 hasOwnProperty 方法:
-
({}).hasOwnProperty.call(foo, 'bar'); // true
-
// 或者:
-
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
Why use Object.prototype.hasOwnProperty.call(myObj, prop) instead of myObj.hasOwnProperty(prop)?
總的來說,使用Object.prototype.hasOwnProperty.call()有三方面的原因:
- If obj inherits from null not Object.prototype
- If hasOwnProperty has been redeclared on obj
- If hasOwnProperty has been redeclared in obj's prototype chain
參考:Object.prototype.hasOwnProperty.call() vs Object.prototype.hasOwnProperty()
在我們日常開發中,對象的使用頻率很高,我們計算數組的長度是非常方便的,但是如何計算對象的長度呢?
假如我們有一個圖書館的項目,項目中有一組圖書和作者,像下面這樣:
[javascript] view plain copy
- var bookAuthors = {
- "Farmer Giles of Ham": "J.R.R. Tolkien",
- "Out of the Silent Planet": "C.S. Lewis",
- "The Place of the Lion": "Charles Williams",
- "Poetic Diction": "Owen Barfield"
- };
我們分析現在的需求,我們給一個API發送數據,但是書的長度不能超過100,因此我們需要在發送數據之前計算在一個對象中總共有多少本書。那么我們總怎么做呢?我們可能會這樣做:
[javascript] view plain copy
- function countProperties (obj) {
- var count = 0;
- for (var property in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, property)) {
- count++;
- }
- }
- return count;
- }
- var bookCount = countProperties(bookAuthors);
- // Outputs: 4
- console.log(bookCount);
這是可以實現的,幸運的是Javascript提供了一個更改的方法來計算對象的長度:
[javascript] view plain copy
- var bookAuthors = {
- "Farmer Giles of Ham": "J.R.R. Tolkien",
- "Out of the Silent Planet": "C.S. Lewis",
- "The Place of the Lion": "Charles Williams",
- "Poetic Diction": "Owen Barfield"
- };
- var arr = Object.keys(bookAuthors);
- //Outputs: Array [ "Farmer Giles of Ham", "Out of the Silent Planet", "The Place of the Lion", "Poetic Diction" ]
- console.log(arr);
- //Outputs: 4
- console.log(arr.length);
下面我們來對數組使用keys方法:
[javascript] view plain copy
- var arr = ["zuojj", "benjamin", "www.zuojj.com"];
- //Outputs: ["0", "1", "2"]
- console.log(Object.keys(arr));
- //Outputs: 3
- console.log(arr.length);
Object.keys() 方法會返回一個由給定對象的所有可枚舉自身屬性的屬性名組成的數組,數組中屬性名的排列順序和使用for-in循環遍歷該對象時返回的順序一致(兩者的主要區別是 for-in 還會遍歷出一個對象從其原型鏈上繼承到的可枚舉屬性)。