亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺談js使用in和hasOwnProperty獲取對象屬性的區(qū)別

 更新時(shí)間:2017年04月27日 10:50:12   投稿:jingxian  
下面小編就為大家?guī)硪黄獪\談js使用in和hasOwnProperty獲取對象屬性的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

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

而hasOwnProperty則是判斷對象實(shí)例的是否具有某個(gè)屬性。

示例代碼:

<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>

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

這篇淺談js使用in和hasOwnProperty獲取對象屬性的區(qū)別就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論