js中hasOwnProperty()方法詳解
hasOwnProperty(propertyName)方法 是用來檢測屬性是否為對象的自有屬性,如果是,返回true,否者false; 參數propertyName指要檢測的屬性名;
用法:object.hasOwnProperty(propertyName) // true/false
hasOwnProperty() 方法是 Object 的原型方法(也稱實例方法),它定義在 Object.prototype 對象之上,所有 Object 的實例對象都會繼承 hasOwnProperty() 方法。
hasOwnProperty() 只會檢查對象的自有屬性,對象原形上的屬性其不會檢測;但是對于原型對象本身來說,這些原型上的屬性又是原型對象的自有屬性,所以原形對象也可以使用hasOwnProperty()檢測自己的自有屬性;
let obj = { name:'張睿', age:18, eat:{ eatname:'面條', water:{ watername:'農夫山泉' } } } 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
到此這篇關于js中hasOwnProperty()方法詳解的文章就介紹到這了,更多相關js hasOwnProperty()內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
淺析C/C++,Java,PHP,JavaScript,Json數組、對象賦值時最后一個元素后面是否可以帶逗號
這篇文章主要介紹了淺析C/C++,Java,PHP,JavaScript,Json數組、對象賦值時最后一個元素后面是否可以帶逗號的相關資料,需要的朋友可以參考下2016-03-03通過JS獲取Request.QueryString()參數的值實現方法
下面小編就為大家?guī)硪黄ㄟ^JS獲取Request.QueryString()參數的值實現方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09javascript使用for循環(huán)批量注冊的事件不能正確獲取索引值的解決方法
這篇文章主要介紹了javascript使用for循環(huán)批量注冊的事件不能正確獲取索引值的解決方法,對比分析了出現問題的代碼與修改后的代碼,并給出了采用閉包實現的方法,具有一定的參考借鑒價值,需要的朋友可以參考下2014-12-12