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

首頁 > 語言 > JavaScript > 正文

詳談js使用in和hasOwnProperty獲取對象屬性的區別

2024-05-06 15:18:05
字體:
來源:轉載
供稿:網友

in判斷的是對象的所有屬性,包括對象實例及其原型的屬性;

而hasOwnProperty則是判斷對象實例的是否具有某個屬性。

示例代碼:

<script type="text/javascript">  function Person(){    }    Person.prototype.name = "allen";    var person = new Person();    console.log(person.hasOwnProperty("name")); //false    console.log("name" in person); //true    console.log(person.name); //"allen"    person.name = "justforse";    console.log(person.hasOwnProperty("name")); //true    console.log("name" in person); //true    console.log(person.name); //"justforuse"    delete person.name;    console.log(person.hasOwnProperty("name")); //false    console.log("name" in person); //true    console.log(person.name); //"allen"</script>

以上代碼執行的時候,name屬性要么是從實例中獲取的,要么是來源于原型,所以使用in 來訪問 name屬性始終返回true;而hasOwnProperty()只在屬性存在與對象實例中時才返回true,當刪除了實例中的name屬性后,就恢復了原型中name屬性的連接,所以返回allen。

以上這篇詳談js使用in和hasOwnProperty獲取對象屬性的區別就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持錯新站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 毕节市| 文登市| 突泉县| 锦州市| 闵行区| 龙泉市| 琼中| SHOW| 文水县| 铜鼓县| 边坝县| 连南| 东光县| 松江区| 凌源市| 吕梁市| 澄迈县| 安阳市| 灵丘县| 鄯善县| 岳西县| 东海县| 神农架林区| 广南县| 安岳县| 诏安县| 大荔县| 瑞安市| 连州市| 平罗县| 天津市| 清水河县| 崇左市| 蕲春县| 确山县| 大余县| 石家庄市| 金堂县| 松原市| 怀化市| 伊通|