ES6对象方法的扩展详解
阅读目录
- Object.assign(target, source_1, ···) // 用于将源对象的所有可枚举属性复制到目标对象中
- Object.is(value1, value2)(object, descriptors) // 用来比较两个值是否严格相等,与(===)基本类似
- Object.setPrototypeOf(object) // 与__proto__相同,用来设置一个对象的prototype对象
- Object.getPrototypeOf(object) // 用于读取一个对象的prototype对象
Object.assign(target, source_1, ···)
概念:方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)
特点:为对象添加属性和方法、克隆对象、合并多个对象、为属性指定默认值
案例:
var sourceObj1 = { name:"assign" } var sourceObj2 = { age:"18" } var target = {}; Object.assign(target, sourceObj1, sourceObj2); console.log(target); //{name: "assign", age: "18"} //目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性 var sourceObj3 = { name:"assign1" } var target1 = {}; Object.assign(target1, sourceObj1, sourceObj3); console.log(target1); //{name: "assign1", age: "18"} //源对象为字符串则会拷贝其枚举属性,数值和布尔值不会产生效果 var sourceString = "assign"; var target2 = {}; Object.assign(target2, sourceString, true, 18); console.log(target2); //{0: "a", 1: "s", 2: "s", 3: "i", 4: "g", 5: "n"} //只有字符串的包装对象,会产生可枚举的实义属性,那些属性则会被拷贝 [[PrimitiveValue]]不会被Object.assign拷贝 console.log(Object(sourceString)); //{0: "a", 1: "s", 2: "s", 3: "i", 4: "g", 5: "n",length:6,[[PrimitiveValue]]:assign} //Object.assign拷贝的属性是有限制的,只拷贝源对象的自身属性,不拷贝不可枚举的属性,不拷贝继承属性 var target3 = {}; Object.assign(target3, Object.defineProperty({}, 'name', { enumerable: false, value: 'hello' }), Object.defineProperty({}, 'age', { enumerable: true, value: 18 }) ) console.log(target3); //{age:18} //Object.assign方法实行的是浅拷贝,而不是深拷贝 //如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用 var target4 = {}; sourceObj4 = {name:{value:"assign"}}; Object.assign(target4, sourceObj4); sourceObj4.name.age = 18; console.log(target4); //{name:{value:"assign",age:18}}; </script>
Object.is(value1, value2)(object, descriptors)
概念:判断两个值是否是相同的值
案例:
Object.is(window,window); //true Object.is({name:"is"},{name:"is"}); //false Object.is([],[]); //false Object.is(undefined,undefined); //true Object.is(null,null); Object.is(0, -0); // false Object.is(-0, -0); // true Object.is(NaN, 0/0); // true
Object.setPrototypeOf(object)
概念:修改一个对象的内置属性[[Prototype]]
注:该方法影响性能,避免使用,可以使用Object.create代替
var obj = {}; var obj1 = {name:"setPrototypeOf"}; Object.setPrototypeOf(obj, obj1); console.log(obj.name); //"setPrototypeOf" //模拟new命令 var F = function () {}; var f = Object.setPrototypeOf({}, F.prototype); F.call(f); // 等同于 var f = new F();
Object.getPrototypeOf(object)
概念:返回参数对象的原型
案例:
var F = function () {};// 构造函数 var f = new F(); Object.getPrototypeOf(f) === F.prototype // true // 空对象的原型是 Object.prototype Object.getPrototypeOf({}) === Object.prototype // true // Object.prototype 的原型是 null Object.getPrototypeOf(Object.prototype) === null // true // 函数的原型是 Function.prototype function f() {} Object.getPrototypeOf(f) === Function.prototype // true