今天了解到了朴素对象的概念。
什么是朴素对象或纯粹对象或简单对象(plainObject)?
字面量创建的,或是new Object() 创建的。
如何判断plainObject?
export default function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false
let proto = obj
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto)
}
return Object.getPrototypeOf(obj) === proto
}
为什么要用这样的写法?(使用while循环找到原型链最顶端的对象进行比对而不是直接和Object.prototype比对)
不健壮的写法如下:
export default function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false
return Object.getPrototypeOf(obj) === Object.prototype;
}
是要处理一些便捷条件,如:
let obj = Object.create(Object.create(null));
// or
let obj = {
__proto__: {
__proto__: null
}
};
以及产生另一个context的情况下:node环境,iframe。因为浏览器中一个页面一个context所以这种情况比较少。
补充Object.create polyfill
if (typeof Object.create != 'function') {
Object.create = (function() {
//为了节省内存,使用一个共享的构造器
function Temp() {}
var hasOwn = Object.prototype.hasOwnProperty;
return function (O) {
if (typeof O != 'object') {
throw TypeError('Object prototype may only be an Object or null');
}
//改造构造函数的原型
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null; // 不要保持一个 O 的杂散引用(a stray reference)...
if (arguments.length > 1) {
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
return obj;
};
})();
}