如何创建一个“纯净”的对象
如何创建一个“纯净”的对象
首先来看一段代码
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 方法创建的新的对象拥有原型上的属性也是正常了
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!