Object.create()
Object.create(..)是在ES5中新增的函数,所以在ES5之前的环境中(比如旧IE)如果要支持这个功能的话就需要使用一段简单的polyfill代码,它部分实现了Object. create(..)的功能:
if (!Object.create) {
Object.create = function(o) {
function F() {};
F.prototype = o;
return new F();
}
}
这段polyfill代码使用了一个一次性函数F,我们通过改写它的.prototype属性使其指向想要关联的对象,然后再使用new F()来构造一个新对象进行关联。
var anotherObject = {
a: 2
};
var myObject = Object.create(anotherObject, {
b: {
enumerable: false,
writable: true,
configurable: false,
value: 3
},
c: {
enumerable: true,
writable: false,
configurable: false,
value: 4
},
});
myObject.hasOwnProperty('a'); // false
myObject.hasOwnProperty('b'); // true
myObject.hasOwnProperty('c'); // true
myObject.a; // 2
myObject.b; // 3
myObject.c; // 4
Object.create(..)的第二个参数指定了需要添加到新对象中的属性名以及这些属性的属性描述符。因为ES5之前的版本无法模拟属性操作符,所以polyfill代码无法实现这个附加功能。
Object.assign()
Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const source2 = { e: 6 };
const returnedTarget = Object.assign(target, source, source2);
console.log(target); // { a: 1, b: 4, c: 5, e: 6 }
console.log(returnedTarget); // { a: 1, b: 4, c: 5, e: 6 }