Object.is(NaN, NaN); //true; Object.is(-0, +0); //false
Object.defineProperty(Object, 'is', { value: function(x, y) { if (x === y) { // 针对+0 不等于 -0的状况 return x !== 0 || 1 / x === 1 / y; } // 针对NaN的状况 return x !== x && y !== y; }, configurable: true, enumerable: false, writable: true });
Object.assign({ name:'zhan' },'test') // {0: "t", 1: "e", 2: "s", 3: "t", name: "zhan"}
Object.assign([1, 2, 3], [4, 5]) // [4, 5, 3]
function cloneObj (obj) { return Object.assign({}, obj); } // 若是要保持克隆的对象的继承性 function cloneObj (obj) { let proto = Object.getPrototypeOf(obj); return Object.assign(Object.creat(proto), obj); }
const DEFAULTS = { logLevel: 0, outputFormat: 'html' }; function processContent(options) { options = Object.assign({}, DEFAULTS, options); console.log(options); // ... }
// Object.assign只能进行值的复制,若是要复制的值是一个取值函数,那么将求值后再复制。 // source对象的foo属性是一个取值函数,Object.assign不会复制这个取值函数,只会拿到值之后,将这个值复制过去 const source = { get foo() { return 1 } }; const target = {}; Object.assign(target, source)
关于对象属性遍历:html
for...in数组
Object.keys(obj)函数
Object.getOwnPropertyNames(obj)this
Object.getOwnPropertySymbols(obj)es5
Reflect.ownKeys(obj)prototype
以上的 5 种方法遍历对象的键名,都遵照一样的属性遍历的次序规则。code
const source = { set foo(value) { console.log(value); } }; const target1 = {}; Object.assign(target1, source); Object.getOwnPropertyDescriptor(target1, 'foo') // { value: undefined, // writable: true, // enumerable: true, // configurable: true } //若是采用Object.defineProperties()和Object.getOwnPropertyDescriptors()将源对象的属性(非继承)添加到目标对象上 Object.defineProperties(target1,Object.getOwnPropertyDescriptors(source)) Object.getOwnPropertyDescriptor(target1, 'foo') // { get: undefined, // set: [Function: set foo], // enumerable: true, // configurable: true }
proto:建立对象的原型orm
第二参数是对象的描述对象htm
结合Object.create复制对象,且保持继承性,见代码:对象
let obj = { name: 'zhan' } let obj1 = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)) // 第二种: let obj1 = Object.assign(Object.create(Object.getPrototypeOf(obj)),obj)
const proto = { foo: 'hello' }; const obj = { foo: 'world', find() { return super.foo; } }; Object.setPrototypeOf(obj, proto); obj.find() // hello //super.foo等同于Object.getPrototypeOf(this).foo(属性) 或Object.getPrototypeOf(this).foo.call(this)(方法)。
// 报错 const obj = { foo: () => super.foo } // 报错 const obj = { foo: function () { return super.foo } } //只有以下对象方法的简写才正确 const obj = { foo () { return super.foo } }
例子1: let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; x // 1 y // 2 z // { a: 3, b: 4 } 例子2: let { ...x, y, z } = obj; // 句法错误 let { x, ...y, ...z } = obj; // 句法错误 例子3: let obj = { a: { b: 1 } }; let { ...x } = obj; obj.a.b = 2; x.a.b // 2 例子4: let o1 = { a: 1 }; let o2 = { b: 2 }; Object.setPrototypeOf(o2,o1) // o2.__proto__ = o1; let { ...o3 } = o2; o3 // { b: 2 } o3.a // undefined