ES6 Object方法扩展的应用实例分析

在ES6中针对对象的方法做了一些扩展和优化,下面简单总结下常用的方法

is方法判断两个对象是否全等

?
1
2
3
console.log(Object.is({},{}), {} === {}); // false, false
console.log(Object.is(NaN,NaN), NaN === NaN); // true, false
console.log(Object.is(+0,-0), +0 === -0); // false, true

assign方法用于对象属性的拷贝

如果两个参数,把第二个参数中可枚举的属性拷贝到第一个参数对象中, 仅限于可枚举的属性,如果有多个参数,那么同样拷贝

?
1
2
3
4
var obj = {};
var obj2 = Object.assign(obj,{name: 'Joh' },{age:10});
console.log(obj === obj2, obj); // true, {name:'Joh', age:10}
console.log(Object.is(obj,obj2)); // true

相同属性的覆盖拷贝

?
1
2
3
4
5
6
7
8
9
const DEFAULT_OPTIONS = {
  name: "Joh"
};
function test(opts) {
  let options = Object.assign({}, DEFAULT_OPTIONS, opts);
  console.log(options);
}
test(); // {name: "Joh"}
test({name: "Lily" ,age:10}); // {name: "Lily", age: 10}

Symbol属性同样拷贝

?
1
2
3
4
5
6
7
var skey1 = Symbol( 'test' );
var skey2 = Symbol( 'test' );
var obj = {};
Object.assign(obj,{name: 'Joh' },{age:10},{[skey1]: 'I am test1' },{[skey2]: 'I am test2' }); // 拷贝
// 验证Symbol的拷贝成功
console.log(obj[skey1]); // I am test
console.log(obj); // {name: "Joh", age: 10, Symbol(test): "I am test1", Symbol(test): "I am test2"}

Object方法:keys,getOwnPropertyNames, getOwnPropertySymbols,getOwnPropertyDescriptor的应用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class A {
  constructor() {
   this .name = 'Joh' ;
  }
  [Symbol( 'fullnameA' )] () {
  }
  getName() {
  }
}
class B extends A {
  constructor() {
   super ();
   this .age = 22;
  }
  [Symbol( 'fullnameB' )] () {
  }
  getAge() {
  }
}
B.prototype.getColor = function () {};
var b = new B();
// 备注:只能获取【自身可枚举属性】,但得不到【原型链上的属性(比如方法) + Symbols属性】
console.log(Object.keys(b)); // ["name", "age"]
// 备注:可获取【可枚举属性】,但得不到【原型链上的属性 + Symbols属性】
console.log(Object.getOwnPropertyNames(b)); // ["name", "age"]
// 使用keys怎么也得不到原型链上不可枚举的属性[通过语法糖创建的方法]
console.log(Object.keys(B.prototype)); // ["getColor"]
// 使用 getOwnPropertyNames 传入prototype 可以得到原型链上的属性
console.log(Object.getOwnPropertyNames(B.prototype)); // ["constructor", "getColor", "getAge"]
// 通过getOwnPropertySymbols可以得到自身Symbols属性,但得不到继承的Symbol属性
console.log(Object.getOwnPropertySymbols(B.prototype)); // [Symbol(fullnameB)]
// 获取自身可枚举属性包括继承过来的,备注:通过class内部的语法糖创建的方法是不可枚举的,但是通过后期B.prototype.出来的是可枚举的
for (let key in b) {
  console.log(key); // 依次输出 name 和 age 和 getColor
}
// 描述对象 测试可枚举性
console.log(Object.getOwnPropertyDescriptor(B.prototype, 'getColor' ));
console.log(Object.getOwnPropertyDescriptor(B.prototype, 'getColor' ).enumerable); // true
console.log(Object.getOwnPropertyDescriptor(B.prototype, 'getAge' ).enumerable); // false

猜你喜欢

转载自www.cnblogs.com/orzhangz/p/11088087.html