国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Javascript學習筆記之 對象篇(三) : hasOwnProperty

2019-11-20 14:24:27
字體:
供稿:網(wǎng)友
// Poisoning Object.prototypeObject.prototype.bar = 1;var foo = {goo: undefined};foo.bar; // 1'bar' in foo; // truefoo.hasOwnProperty('bar'); // falsefoo.hasOwnProperty('goo'); // true

在這里,只有 hasOwnProperty 能給出正確答案,這在遍歷一個對象的屬性時是非常必要的。Javascript 中沒有其他方法能判斷一個屬性是定義在對象本身還是繼承自原型鏈。

hasOwnProperty 作為屬性

Javascript 并未將 hasOwnProperty 設為敏感詞,這意味著你可以擁有一個命名為 hasOwnProperty 的屬性。這個時候你無法再使用本身的 hasOwnProperty 方法來判斷屬性,所以你需要使用外部的 hasOwnProperty 方法來進行判斷。

var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons'};foo.hasOwnProperty('bar'); // always returns false// Use another Object's hasOwnProperty and call it with 'this' set to foo({}).hasOwnProperty.call(foo, 'bar'); // true// It's also possible to use hasOwnProperty from the Object// prototype for this purposeObject.prototype.hasOwnProperty.call(foo, 'bar'); // true

總結

當判斷對象屬性存在時,hasOwnProperty 是唯一可以依賴的方法。這里還要提醒下,當我們使用 for in loop 來遍歷對象時,使用 hasOwnProperty 將會很好地避免來自原型對象擴展所帶來的困擾。

下面是其他網(wǎng)友的補充:

Javascript中Object對象原型上的hasOwnProperty()用來判斷一個屬性是定義在對象本身而不是繼承自原型鏈。

obj.hasOwnProperty(prop)

參數(shù) prop

要檢測的屬性 字符串 名稱或者 Symbol(ES6)

o = new Object();o.prop = 'exists';o.hasOwnProperty('prop');       // 返回 trueo.hasOwnProperty('toString');     // 返回 falseo.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

參考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 闻喜县| 柞水县| 铁岭市| 孝感市| 民丰县| 河南省| 娄底市| 于田县| 岳池县| 平定县| 盈江县| 临朐县| 大理市| 南皮县| 延安市| 利辛县| 淳化县| 漠河县| 登封市| 花垣县| 万年县| 洞头县| 常山县| 嫩江县| 正定县| 深水埗区| 洛宁县| 新蔡县| 揭东县| 浦县| 桃源县| 上饶市| 张掖市| 沁水县| 蒙城县| 禹城市| 莱州市| 永嘉县| 凤阳县| 安图县| 平罗县|