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