js中hasOwnProperty()方法詳解
hasOwnProperty(propertyName)方法 是用來檢測屬性是否為對象的自有屬性,如果是,返回true,否者false; 參數(shù)propertyName指要檢測的屬性名;
用法:object.hasOwnProperty(propertyName) // true/false
hasOwnProperty() 方法是 Object 的原型方法(也稱實例方法),它定義在 Object.prototype 對象之上,所有 Object 的實例對象都會繼承 hasOwnProperty() 方法。
hasOwnProperty() 只會檢查對象的自有屬性,對象原形上的屬性其不會檢測;但是對于原型對象本身來說,這些原型上的屬性又是原型對象的自有屬性,所以原形對象也可以使用hasOwnProperty()檢測自己的自有屬性;
let obj = { name:'張睿', age:18, eat:{ eatname:'面條', water:{ watername:'農(nóng)夫山泉' } } } console.log(obj.hasOwnProperty('name')) //true console.log(obj.hasOwnProperty('age')) //true console.log(obj.hasOwnProperty('eat')) //true console.log(obj.hasOwnProperty('eatname')) //false console.log(obj.hasOwnProperty('water')) //false console.log(obj.hasOwnProperty('watername')) //false console.log(obj.eat.hasOwnProperty('eatname')) //true console.log(obj.eat.hasOwnProperty('water')) //true console.log(obj.eat.hasOwnProperty('watername')) //false console.log(obj.eat.water.hasOwnProperty('watername')) //true
例子:
function Site(){ ? ? this.name = "CodePlayer"; ? ? this.url = "http://www.365mini.com/"; ? ? this.sayHello = function(){ ? ? ? ? document.writeln("歡迎來到" + this.name); ? ? }; } var obj = { ? ? engine: "PHP" ? ? ,sayHi: function(){ ? ? ? ? document.writeln("歡迎訪問" + this.url); ? ? } }; // 使用對象obj覆蓋Site本身的prototype屬性 Site.prototype = obj; var s = ?new Site(); document.writeln( s.hasOwnProperty("name") ); // true document.writeln( s.hasOwnProperty("sayHello") ); // true // 以下屬性繼承自原型鏈,因此為false document.writeln( s.hasOwnProperty("engine") ); // false document.writeln( s.hasOwnProperty("sayHi") ); // false document.writeln( s.hasOwnProperty("toString") ); // false // 想要查看對象(包括原型鏈)是否具備指定的屬性,可以使用in操作符 document.writeln( "engine" in s ); // true document.writeln( "sayHi" in s ); // true document.writeln( "toString" in s ); // true
到此這篇關(guān)于js中hasOwnProperty()方法詳解的文章就介紹到這了,更多相關(guān)js hasOwnProperty()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺析C/C++,Java,PHP,JavaScript,Json數(shù)組、對象賦值時最后一個元素后面是否可以帶逗號
這篇文章主要介紹了淺析C/C++,Java,PHP,JavaScript,Json數(shù)組、對象賦值時最后一個元素后面是否可以帶逗號的相關(guān)資料,需要的朋友可以參考下2016-03-03基于JavaScript實現(xiàn)永遠(yuǎn)加載不滿的進(jìn)度條
各位開發(fā)大佬,平時肯定見到過這種進(jìn)度條吧,一直在加載,但等了好久都是在99%,那如何用JavaScript實現(xiàn)這一效果呢,下面就來和大家詳細(xì)講講2023-04-04通過JS獲取Request.QueryString()參數(shù)的值實現(xiàn)方法
下面小編就為大家?guī)硪黄ㄟ^JS獲取Request.QueryString()參數(shù)的值實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09javascript使用for循環(huán)批量注冊的事件不能正確獲取索引值的解決方法
這篇文章主要介紹了javascript使用for循環(huán)批量注冊的事件不能正確獲取索引值的解決方法,對比分析了出現(xiàn)問題的代碼與修改后的代碼,并給出了采用閉包實現(xiàn)的方法,具有一定的參考借鑒價值,需要的朋友可以參考下2014-12-12JavaScript實現(xiàn)網(wǎng)頁動態(tài)生成表格
這篇文章主要為大家詳細(xì)介紹了JavaScript實現(xiàn)網(wǎng)頁動態(tài)生成表格,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-11-11