今天看啥  ›  专栏  ›  JS菌

如何创建一个“纯净”的对象

JS菌  · 掘金  ·  · 2019-04-20 04:05

文章预览

阅读 3

如何创建一个“纯净”的对象

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 对象,为了只遍历其自身的属性,需要增加一层筛选

Object.prototype.log = ''

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

for (const key in obj) {
    if (obj.hasOwnProperty(key)) { // 检查是否是自身的属性
        console.log(key) // name age
    }
}
复制代码

虽然这样能够避免打印原型上的属性,但仍然比较麻烦 🙃

接下来我们尝试用 Object.create 方法来创建对象

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

这样就不会打印出原型上的属性了

我们再来看下 Object.create 和字面量语法创建一个空对象有什么区别

20190328100703.png

可以看到使用 create 方法并传入 null 作为参数可以避免原型被继承

字面量语法与 Object.create(Object.prototype) 是一样的

那么 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 的技术文章,只谈技术不谈八卦 😊

………………………………

原文地址:访问原文地址
快照地址: 访问文章快照
总结与预览地址:访问总结与预览