利用Object的一些新的方法,可以减少错误率
测试了下Object的一些ES6中的方法。
'use strict';
//Object.is()
console.log('test is()');
let ret = Object.is('foo','foo') //true
console.log('ret:',ret)
ret =Object.is({},{}) //false
console.log('ret:',ret)
console.log('test assign()')
var target = {a:1}
var s1 = {a:2,b:3}
var s2 = {b:4,c:5}
ret = Object.assign(target,s1,s2)
console.log('ret:',ret)
//对于嵌套对象,处理方法是替换
target = {a:{b:2,c:3}}
s1 = {a:{b:10}}
ret = Object.assign(target,s1)
console.log('对于嵌套对象,处理方法是替换:',ret)
//对于数组是对应序号位置的覆盖。其实这个可以看成对应key为 0,1,2的替换。
ret = Object.assign([1,2,3],[4,5]) // [4,5,3]
console.log('数组覆盖',ret)
//可以给对象添加属性。
class Pt{
constructor(x,y){
Object.assign(this,{x,y})
}
}
let pt = new Pt(1, 2)
console.log(pt); //Pt { x: 1, y: 2 }
//添加方法
Object.assign(Pt.prototype,{
toString(){
return String(this.x) + " , " + String(this.y)
},
times(s){
this.x = s*this.x
this.y = s*this.y
}
})
console.log(pt.toString());
pt.times(10);
console.log(pt.toString());