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

时间:2022-06-20
本文章向大家介绍如何创建一个“纯净”的对象,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

⭐️ 更多前端技术和知识点,搜索订阅号 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)
}

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

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

可以看到使用 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 方法创建的新的对象拥有原型上的属性也是正常了 ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill

很多时候就像第一段代码一样我们并不需要遍历原型上的属性和方法

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

或者手动将 __proto__ 设置为 null

obj1 = {name: 'oli'}
obj1.__proto__ = null

?