屬性與方法的簡潔表示法
var birth = '2000/01/01';
var Person = {
name: '張三',
//等同于birth: birth
birth,
// 等同于hello: function ()...
hello() { console.log('我的名字是', this.name); }
};
//返回值的簡寫
function getPoint() {
var x = 1; var y = 10;
return {x, y};
}
getPoint()
// {x:1, y:10}
//commonjs變量輸出
module.exports = { getItem, setItem, clear };
// 等同于
module.exports = {
getItem: getItem,
setItem: setItem,
clear: clear
};
//get set的寫法
var cart = {
_wheels: 4,
get wheels () { return this._wheels; },
set wheels (value) {
if (value < this._wheels) {
throw new Error('數(shù)值太小了比规!');
}
this._wheels = value;
}
}
屬性表達(dá)()
var lastWord = 'last word';
var a = {
'first word': 'hello',
[lastWord]: 'world'};
a['first word'] // "hello"
a[lastWord] // "world"
//好怪
a['last word'] // "world"
Object.is()
用于比較兩個(gè)值是否相等
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
自行實(shí)現(xiàn)盯桦,可采用如下代碼
Object.defineProperty(Object, 'is', {
value: function(x, y) {
if (x === y) {
// 針對(duì)+0 不等于 -0的情況
return x !== 0 || 1 / x === 1 / y;
}
// 針對(duì)NaN的情況
return x !== x && y !== y;
},
configurable: true,
enumerable: false,
writable: true}
);
Object.assign()
用于對(duì)象的合并壮不,將源對(duì)象(source)的所有可枚舉屬性,復(fù)制到目標(biāo)對(duì)象(target)。如果目標(biāo)對(duì)象與源對(duì)象有同名屬性,或多個(gè)源對(duì)象有同名屬性叮叹,則后面的屬性會(huì)覆蓋前面的屬性。
var target = { a: 1, b: 1 };
var source1 = { b: 2, c: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
如果該參數(shù)不是對(duì)象爆存,則會(huì)先轉(zhuǎn)成對(duì)象蛉顽,然后返回。
typeof Object.assign(2)
Object.assign拷貝的屬性是有限制的先较,只拷貝源對(duì)象的自身屬性(不拷貝繼承屬性)蜂林,也不拷貝不可枚舉的屬性(enumerable: false)。
常見用途:
- 為對(duì)象添加屬性
class Point {
constructor(x, y) {
Object.assign(this, {x, y});
}
}
- 為對(duì)象添加方法
Object.assign(SomeClass.prototype, {
someMethod(arg1, arg2) { ··· },
anotherMethod() { ··· }
});
// 等同于下面的寫法
SomeClass.prototype.someMethod = function (arg1, arg2) { ···};
SomeClass.prototype.anotherMethod = function () { ···};
- 克隆對(duì)象
function clone(origin) { return Object.assign({}, origin);}
采用這種方法克隆拇泣,只能克隆原始對(duì)象自身的值噪叙,不能克隆它繼承的值。如果想要保持繼承鏈霉翔,可以采用下面的代碼睁蕾。
function clone(origin) {
let originProto = Object.getPrototypeOf(origin);
return Object.assign(Object.create(originProto), origin);
}
- 合并多個(gè)對(duì)象
const merge = (target, ...sources) => Object.assign(target, ...sources);
- 為屬性指定默認(rèn)值
const DEFAULTS = { logLevel: 0, outputFormat: 'html'};
function processContent(options) {
options = Object.assign({}, DEFAULTS, options);
}