如何建立一個「純淨」的對象

winter-4004487_640.jpg

如何建立一個「純淨」的對象

⭐️ 更多前端技術和知識點,搜索訂閱號 JS 菌 訂閱前端

首先來看一段代碼 📃函數

Object.prototype.log = ''

let obj = {
    name: 'oli',
    age: 12
}

for (const key in obj) {
    console.log(key) // name age log
}
複製代碼

假設 Object 的原型中有一個自定義的 log 屬性,咱們用字面量語法定義 obj 對象,那麼使用 for-in 遍歷方法就會遍歷到這個 log 對象,爲了只遍歷其自身的屬性,須要增長一層篩選ui

Object.prototype.log = ''

let obj = {
    name: 'oli',
    age: 12
}

for (const key in obj) {
    if (obj.hasOwnProperty(key)) { // 檢查是不是自身的屬性
        console.log(key) // name age
    }
}
複製代碼

雖然這樣可以避免打印原型上的屬性,但仍然比較麻煩 🙃spa

接下來咱們嘗試用 Object.create 方法來建立對象prototype

Object.prototype.log = ''

let obj = Object.create(null) // 傳入 null 做爲參數

obj.name = 'oli'
obj.age = 12

for (const key in obj) {
    console.log(key)
}
複製代碼

20190328100318.png

這樣就不會打印出原型上的屬性了code

咱們再來看下 Object.create 和字面量語法建立一個空對象有什麼區別cdn

20190328100703.png

能夠看到使用 create 方法並傳入 null 做爲參數能夠避免原型被繼承對象

字面量語法與 Object.create(Object.prototype) 是同樣的blog

那麼 create 方法到底作了什麼呢 😒繼承

咱們直接去看 MDN 有關這個方法的 polyfill

if (typeof Object.create !== "function") {
    Object.create = function (proto, propertiesObject) {
        if (typeof proto !== 'object' && typeof proto !== 'function') {
            throw new TypeError('Object prototype may only be an Object: ' + proto);
        } else if (proto === null) {
            throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
        }

        if (typeof propertiesObject != 'undefined') {
            throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");
        }

+ function F() {}
+ F.prototype = proto;

+ return new F();
    };
}
複製代碼

重點看這裏,create 方法的內部建立了一個函數,這個函數的原型指向 proto 並返回經過 new 操做符建立的函數的實例

所以用 create 方法建立的新的對象擁有原型上的屬性也是正常了 😬

developer.mozilla.org/en-US/docs/…

不少時候就像第一段代碼同樣咱們並不須要遍歷原型上的屬性和方法

使用 create 方法並傳入 null 就能避免打印出原型上的方法

或者手動將 __proto__ 設置爲 null

obj1 = {name: 'oli'}
obj1.__proto__ = null
複製代碼

20190328102143.png

🌝

JS 菌公衆帳號

請關注個人訂閱號,不按期推送有關 JS 的技術文章,只談技術不談八卦 😊

相關文章
相關標籤/搜索