JS Object靜態方法講解

一、Object.assign()

將多個對象的可枚舉屬性拷貝到目標對象上,並且返回賦值後的目標對象。

Object.assign(target, …sources)

  • target:目標對象
  • …sources:源對象

測試如下:

var source1 = {
  name1: 'source1',
  age1: 18
};

var source2 = {
  name2: 'source2',
  age2: 19
};

var target = Object.assign({name: 'target'}, source1, source2);

console.info(JSON.stringify(target)); 
// 輸出如下:
{
    "name":"target",
    "name1":"source1",
    "age1":18,
    "name2":"source2",
    "age2":19
}

二、Object.create()

獲取一個類的原型(prototype)對象,返回值爲參數類的原型對象。可用於類繼承。

Object.create(proto[, propertiesObject])

  • proto:類原型

測試如下:

// 父類
function Super1Class() {
  this.name = 'Super1Class';
}

Super1Class.prototype = {
  super1Method: function() {
    console.info('My name is ' + this.name);
  }
};

// 子類
function MyClass() {
  this.name = 'MyClass';
}

MyClass.prototype = Object.create(Super1Class.prototype); 
// 類似於下面這種方式
// MyClass.prototype = new  Super1Class();

var myClass = new MyClass();

console.info(myClass instanceof Super1Class); 
// true
console.info(myClass instanceof MyClass);   
// true
console.info(myClass.super1Method()); 
// My name is MyClass

三、Object.defineProperties()

給對象定義屬性,如果存在該屬性,則用新定義的屬性更新已存在的屬性,如果不存在該屬性,則添加該屬性。

Object.defineProperties(obj, props)

  • obj:被添加屬性的對象
  • props:添加或更新的屬性對象

測試如下:

var obj = {
  name: 'obj'
};

Object.defineProperties(obj, {
  name: {
    value: 'newName',
    writable: true
  },
  newProp1: {
    value: 'newProp1',
    writable: true,
    enumerable: true
  },
  newProp2: {
    value: 'newProp2',
    writable: true
  }
});

console.info(JSON.stringify(obj));
// 輸出結果如下
{
    "name":"newName",
    "newProp1":"newProp1"
}

從以上輸出結果可以看到,Object.defineProperties()定義的覆蓋屬性name只是更新了舊屬性name的值及其writable屬性,並沒有更新name屬性的可枚舉性。

但是我們通過Object.defineProperties()定義的新屬性newProp2默認是不可枚舉的,所以在JSON.stringify(obj)時並沒有序列化該新定義的屬性。

以上結果可以得出結論:

JSON.stringify()序列化對象到JSONObject時,只會序列化該對象可枚舉的屬性。

四、Object.defineProperty()

在對象上定義新屬性,或修改對象現有屬性,並返回該對象。

Object.defineProperty(obj, prop, descriptor)

  • obj:被添加屬性的對象
  • prop:屬性名
  • descriptor:屬性描述

測試如下:

var obj = {};

var mame = 'obj';
Object.defineProperty(obj, 'name', {
  configurable: true,
  enumerable: true,
  get: function() {
    console.info('get name .');
    return mame;
  },
  set: function(newName) {
    console.info('set new name is ' + newName);
    mame = newName;
  }
});

console.info(JSON.stringify(obj));
obj.name = 'xxx';
console.info(JSON.stringify(obj));
// 輸出結果如下:
get name .
{"name":"obj"}
set new name is xxx
get name .
{"name":"xxx"}

從以上測試結果可以看出,我們在序列化對象是會調用一次屬性的get方法,在給對象屬性賦值時,會調用一次屬性的set方法。

五、Object.entries()

遍歷獲取對象上所有可枚舉的屬性,返回結果是一個二維數組[['key1', 'value1'], ['key2', 'value2'], ......]

Object.entries(obj)

  • obj:被遍歷的對象

測試如下:

var obj = {
  name: 'obj',
  age: 18
};

var kvs = Object.entries(obj);

console.info(JSON.stringify(kvs)); 
// [["name","obj"],["age",18]]

for(let [key, value] of Object.entries(obj)) {
  console.info(key + ' --> ' + value); 
  // name --> obj, age --> 18
}

Object.entries(obj).forEach(function([key, value]) {
  console.info(key + ' --> ' + value); 
  // name --> obj, age --> 18
});

for(let key in obj) {
  console.info('key --> ' + key); 
  // key --> name, key --> age
}

六、Object.freeze()

將一個對象上的屬性凍結,阻止添加、刪除、更新屬性到該對象及其原型。返回被凍結的對象。

Object.freeze(obj)

  • obj:被凍結的對象

測試如下:

'use strict'

var obj = {
  name: 'obj'
};

obj['age'] = 18;
obj.name = 'newName';

console.info(JSON.stringify(obj)); 
// {"name":"newName","age":18}

var o = Object.freeze(obj);

console.info(o === obj); 
// true

// 開啓嚴格模式報錯
obj['sex'] = 'man'; 
// Uncaught TypeError: Cannot add property sex, object is not extensible
obj.name = 'updateName'; 
// Uncaught TypeError: Cannot assign to read only property 'name' of object '#<Object>'

console.info(JSON.stringify(obj)); 
// {"name":"newName","age":18}

被凍結的對象所有屬性只可讀。

七、Object.getOwnPropertyDescriptor()

獲取一個對象指定名稱的直接屬性的描述信息(直接在對象上的屬性,而不是原型鏈上的屬性),存在則返回該屬性的描述信息,不存在則返回undefined。

Object.getOwnPropertyDescriptor(obj, prop)

  • obj:目標對象
  • prop:被獲取的屬性名

測試如下:

function Obj() {
  this.name = 'obj';
}

Obj.prototype = {
  age: 18,
  sex: function() {
    return 'man';
  }
};

var obj = new Obj();

var descName = Object.getOwnPropertyDescriptor(obj, 'name');
console.info(JSON.stringify(descName)); 
// {"value":"obj","writable":true,"enumerable":true,"configurable":true}

var descAge = Object.getOwnPropertyDescriptor(obj, 'age');
console.info(JSON.stringify(descAge)); 
// undefined

var descSex = Object.getOwnPropertyDescriptor(obj, 'sex');
console.info(JSON.stringify(descSex)); 
// undefined

八、Object.getOwnPropertyDescriptors()

獲取一個對象所有的直接屬性的描述信息(直接在對象上的屬性,而不是原型鏈上的屬性)。

Object.getOwnPropertyDescriptors(obj)

  • obj:目標對象

測試如下:

function Obj() {
  this.name = 'obj';
  this.age = 18;
}

Obj.prototype = {
  sex: function() {
    return 'man';
  }
};

var obj = new Obj();

var descObj = Object.getOwnPropertyDescriptors(obj);
console.info(JSON.stringify(descObj));
// 輸出結果如下
{"name":
  {
    "value":"obj",
    "writable":true,
    "enumerable":true,
    "configurable":true
  },
  "age":{
    "value":18,
    "writable":true,
    "enumerable":true,
    "configurable":true
  }
}

九、Object.getOwnPropertyNames()

獲取一個對象所有的直接屬性的屬性名稱(直接在對象上的屬性,而不是原型鏈上的屬性)。返回屬性名稱字符串數組。

Object.getOwnPropertyNames(obj)

  • obj:目標對象

測試如下:

function Obj() {
  this.name = 'obj';
  this.age = 18;
}

Obj.prototype = {
  sex: function() {
    return 'man';
  }
};

var obj = new Obj();

var objProps = Object.getOwnPropertyNames(obj);
console.info(JSON.stringify(objProps));
// ["name","age"]

十、Object.getOwnPropertySymbols()

獲取對象上所有的Symbol類型的屬性列表。

Object.getOwnPropertySymbols(obj)

  • obj:目標對象

測試如下:

const obj = {
  name: 'obj'
};

const name = Symbol('name');

obj[name] = '我是 Symbol 類型的 name 值';

var objSymbolProps = Object.getOwnPropertySymbols(obj);

console.info(objSymbolProps);
// [Symbol(name)]
console.info(obj[objSymbolProps[0]]);
// 我是 Symbol 類型的 name 值

十一、Object.getPrototypeOf()

獲取一個對象上的原型對象,其功能和 obj._ proto _等同。 。

Object.getPrototypeOf(obj)

  • obj:目標對象

測試如下:

function MyClass() {}

MyClass.prototype = {
  name: 'MyClass'
};

var obj = Object.create(MyClass.prototype);

console.info(Object.getPrototypeOf(obj) === MyClass.prototype);
// true

console.info(obj.__proto__ === MyClass.prototype);
// true

十二、Object.is()

比較兩個對象是否相同,值類型對象比較值是否相等,引用類型對象比較內存地址是否相同。

Object.is(value1, value2);

  • value1:第一個被比較的對象
  • value2:第二個被比較的對象

測試如下:

Object.is('foo', 'foo');     // true
Object.is(window, window);   // true

Object.is('foo', 'bar');     // false
Object.is([], []);           // false
Object.is({}, {});           // false

var obj1 = {
  name: 'obj'
};

var obj2 = {
  name: 'obj'
};

Object.is(obj1, obj1);       // true
Object.is(obj1, obj2);       // false

Object.is(null, null);       // true

Object.is(0, -0);            // false
Object.is(-0, -0);           // true
Object.is(NaN, 0/0);         // true

十三、Object.keys()

返回對象的可枚舉屬性數組。

Object.keys(obj)

  • obj:目標對象

測試如下:

var arr = ['a', 'b', 'c'];

console.info(Object.keys(arr));
// ["0", "1", "2"]

var obj = { 1: 'a', 0: 'b', 2: 'c' };

console.log(Object.keys(obj));
// ["0", "1", "2"] 

以上結果可以看到Object.keys(obj)還會對屬性名進行排序。

發佈了89 篇原創文章 · 獲贊 29 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章