5.對(duì)象的擴(kuò)展

屬性與方法的簡(jiǎn)潔表示法

var birth = '2000/01/01';
var Person = { 
   name: '張三', 
   //等同于birth: birth 
   birth,  
   // 等同于hello: function ()...
   hello() { console.log('我的名字是', this.name); }
};

//返回值的簡(jiǎn)寫(xiě)
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的寫(xiě)法
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)。

常見(jiàn)用途:
  • 為對(duì)象添加屬性
class Point { 
    constructor(x, y) { 
      Object.assign(this, {x, y}); 
    }
}
  • 為對(duì)象添加方法
Object.assign(SomeClass.prototype, { 
  someMethod(arg1, arg2) { ··· },
   anotherMethod() { ··· }
});
// 等同于下面的寫(xiě)法
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);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容