js属性对象的hasOwnProperty方法
生活随笔
收集整理的這篇文章主要介紹了
js属性对象的hasOwnProperty方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
IE 5.5+、FireFox、Chrome、Safari、Opera等主流瀏覽器均支持該函數(shù)。
?
Object的hasOwnProperty()方法返回一個(gè)布爾值,判斷對(duì)象是否包含特定的自身(非繼承)屬性??梢杂糜趨^(qū)分自身屬性和繼承屬性,如下
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?
還可以用于遍歷一個(gè)對(duì)象的所有自身屬性
在看開源項(xiàng)目的過程中,經(jīng)常會(huì)看到類似如下的源碼。for...in循環(huán)對(duì)象的所有枚舉屬性,然后再使用hasOwnProperty()方法來忽略繼承屬性。
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} }?
當(dāng)對(duì)象有屬性名?hasOwnProperty 沖突時(shí)
?JavaScript 并沒有保護(hù)?hasOwnProperty?屬性名,因此,可能存在于一個(gè)包含此屬性名的對(duì)象,有必要使用一個(gè)可擴(kuò)展的hasOwnProperty方法來獲取正確的結(jié)果:
var foo = {hasOwnProperty: function() {return false;},bar: 'Here be dragons' }; foo.hasOwnProperty('bar'); // 始終返回 false // 如果擔(dān)心這種情況,可以直接使用原型鏈上真正的 hasOwnProperty 方法 // 使用另一個(gè)對(duì)象的`hasOwnProperty` 并且call ({}).hasOwnProperty.call(foo, 'bar'); // true // 也可以使用 Object 原型上的 hasOwnProperty 屬性 Object.prototype.hasOwnProperty.call(foo, 'bar'); // true解決辦法如上通過call方法調(diào)用原型鏈上的hasOwnProperty()方法
?
學(xué)習(xí)網(wǎng)址:http://www.cnblogs.com/weiqinl/p/8683207.html
?
總結(jié)
以上是生活随笔為你收集整理的js属性对象的hasOwnProperty方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python数字对应车站_python爬
- 下一篇: java中的字符串_java中字符串的操