1.Object.is()
image.png
Object.is('foo', 'foo'); // true
Object.is(window, window); // true
Object.is('foo', 'bar'); // false
Object.is([], []); // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(null, null); // true
// 特例
Object.is(0, -0); // false
Object.is(0, +0); // true
Object.is(-0, -0); // true
Object.is(NaN, 0/0); // true
2.Object.assign()
Object.assign() 方法用于將所有可枚舉屬性的值從一個或多個源對象分配到目標(biāo)對象骇陈。它將返回目標(biāo)對象。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(target === returnedTarget) //true
> Object { a: 1, b: 4, c: 5 }
> Object { a: 1, b: 4, c: 5 }
> true
3.Object.isFrozen()
`**Object.isFrozen()**`方法判斷一個對象是否被[凍結(jié)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
4.Object.freeze()
Object.freeze() 方法可以凍結(jié)一個對象。一個被凍結(jié)的對象再也不能被修改酸舍;凍結(jié)了一個對象則不能向這個對象添加新的屬性,不能刪除已有屬性,不能修改該對象已有屬性的可枚舉性狸驳、可配置性、可寫性缩赛,以及不能修改已有屬性的值耙箍。此外,凍結(jié)一個對象后該對象的原型也不能被修改酥馍。freeze() 返回和傳入的參數(shù)相同的對象
let a = [0];
Object.freeze(a); // 現(xiàn)在數(shù)組不能被修改了.
a[0]=1; // fails silently
a.push(2); // fails silently
// In strict mode such attempts will throw TypeErrors
function fail() {
"use strict"
a[0] = 1;
a.push(2);
}
fail();
var obj = {
prop: function() {},
foo: 'bar'
};
// 新的屬性會被添加, 已存在的屬性可能
// 會被修改或移除
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;
// 作為參數(shù)傳遞的對象與返回的對象都被凍結(jié)
// 所以不必保存返回的對象(因為兩個對象全等)
var o = Object.freeze(obj);
o === obj; // true
Object.isFrozen(obj); // === true
// 現(xiàn)在任何改變都會失效
obj.foo = 'quux'; // 靜默地不做任何事
// 靜默地不添加此屬性
obj.quaxxor = 'the friendly duck';
// 在嚴(yán)格模式辩昆,如此行為將拋出 TypeErrors
function fail(){
'use strict';
obj.foo = 'sparky'; // throws a TypeError
delete obj.quaxxor; // 返回true,因為quaxxor屬性從來未被添加
obj.sparky = 'arf'; // throws a TypeError
}
fail();
// 試圖通過 Object.defineProperty 更改屬性
// 下面兩個語句都會拋出 TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });
// 也不能更改原型
// 下面兩個語句都會拋出 TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }
被凍結(jié)的對象是不可變的旨袒。但也不總是這樣汁针。下例展示了凍結(jié)對象不是常量對象(淺凍結(jié))
obj1 = {
internal: {}
};
Object.freeze(obj1);
obj1.internal.a = 'aValue';
obj1.internal.a // 'aValue'
5.Object.seal()
Object.seal()方法封閉一個對象,阻止添加新屬性并將所有現(xiàn)有屬性標(biāo)記為不可配置砚尽。當(dāng)前屬性的值只要原來是可寫的就可以改變施无。