解剖JS原型對象,讓世界沒有混淆的對象??

前言:記錄對對象屬性的再次學(xué)習(xí),對象屬性很多概念性都比較容易讓人混淆(至少我是經(jīng)常的混淆... 大笑ing - )

1. hasOwnProperty和in屬性

hasOwnProperty的作用:檢查對象中是否存在指定的實(shí)例屬性,重點(diǎn)是實(shí)例而非原型屬性。hasOwnProperty個人直譯:擁有自己的屬性...方便好記??

語法:對象.hasOwnProperty(“屬性名”)

代碼示例

<script>

    //01 提供一個構(gòu)造函數(shù)
    function User(name) {
        this.name = name;
    }

    //02 設(shè)置構(gòu)造函數(shù)的原型對象的屬性
    User.prototype.todo = function () {
        console.log("to do some...");
    }

    User.prototype.des = "默認(rèn)的描述信息";

    //03 創(chuàng)建對象
    var user = new User();

    //04 使用hasOwnProperty方法判斷該屬性是否是對象的實(shí)例屬性
    console.log(user.hasOwnProperty("age"));       //false
    console.log(user.hasOwnProperty("name"));      //true
    console.log(user.hasOwnProperty("todo"));  //false
    console.log(user.hasOwnProperty("des"));       //false

</script>

in關(guān)鍵字作用:用來檢查對象中是否存在某個屬性(不區(qū)分實(shí)例屬性和原型屬性)...??如果是用在for循環(huán)上的in就不是這個意思了

語法:“屬性名” in 對象

代碼示例

<script>

    //01 提供一個構(gòu)造函數(shù)
    function User(name) {
        this.name = name;
    }

    //02 設(shè)置構(gòu)造函數(shù)的原型對象的屬性
    User.prototype.todo = function () {
        console.log("to do some...");
    }

    //03 創(chuàng)建對象
    var user = new User();

    //04 使用in關(guān)鍵字判斷對象中是否存在以下屬性:name age todo
    console.log("age" in user);       //false
    console.log("name" in user);      //true
    console.log("todo" in user);  //true

</script>

那么我們?nèi)绾闻袛鄬ο笾兄淮嬖?code>原型屬性呢?

function isProperty(obj, property) {
   return !obj.hasOwnProperty(property) && (property in obj); 
}

  • 如果想知道user是屬于某個構(gòu)造函數(shù)時直接user.constructor查看

  • 如果想要判斷user這個對象是不是User構(gòu)造函數(shù)的實(shí)例時用instanceof檢查

 console.log(user instanceof User);      //true
 console.log(user instanceof Object);      //true
 //instanceof 直接查到整條原型鏈
  • 如果還要判斷User是不是user的原型對象時,可以用isPrototypeOf
console.log(User.prototype.isPrototypeOf(user));    //rue


總結(jié):會很容易懵逼... 前方的道路還是很多霧霾...且行且懵逼...

---查看原文--來自漂亮妹紙寫的文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容