欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2017年04月25日 09:32:31   投稿:jingxian  
下面小編就為大家?guī)硪黄斦刯s使用in和hasOwnProperty獲取對象屬性的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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>

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

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

相關文章

最新評論