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

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

相关文章
相关标签/搜索