JS中hasOwnProperty方法用法簡介
JS中hasOwnProperty方法用法簡介
hasOwnProperty表示是否有自己的屬性。這個方法會查找一個對象是否有某個屬性,但是不會去查找它的原型鏈。
var obj = { a: 1, fn: function(){ }, c:{ d: 5 } }; console.log(obj.hasOwnProperty('a')); // true console.log(obj.hasOwnProperty('fn')); // true console.log(obj.hasOwnProperty('c')); // true console.log(obj.c.hasOwnProperty('d')); // true console.log(obj.hasOwnProperty('d')); // false, obj對象沒有d屬性 var str = new String(); // split方法是String這個對象的方法,str對象本身是沒有這個split這個屬性的 console.log(str.hasOwnProperty('split')); // false console.log(String.prototype.hasOwnProperty('split')); // true
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
到此這篇關(guān)于JS中hasOwnProperty方法用法簡介的文章就介紹到這了,更多相關(guān)js hasOwnProperty用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js判斷價格,必須為數(shù)字且不能為負(fù)數(shù)的實現(xiàn)方法
下面小編就為大家?guī)硪黄猨s判斷價格,必須為數(shù)字且不能為負(fù)數(shù)的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10H5如何實現(xiàn)喚起APP及調(diào)試bug解決
這篇文章主要為大家介紹了H5如何實現(xiàn)喚起APP及調(diào)試bug解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05JavaScript函數(shù)中關(guān)于valueOf和toString的理解
本文給大家介紹JavaScript函數(shù)中關(guān)于valueOf和toString的理解,簡單的說就是需要轉(zhuǎn)換為字符串時,會調(diào)用toString,需要轉(zhuǎn)換為數(shù)字時需要調(diào)用valueOf。對js valueof tostring知識感興趣的朋友一起學(xué)習(xí)吧2016-06-06JavaScript實現(xiàn)生成動態(tài)表格和動態(tài)效果的方法詳解
這篇文章主要介紹了如何通過JavaScript語言實現(xiàn)動圖表格的生成以及動態(tài)效果的實現(xiàn),文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-02-02