常规用法,以及一些注意事项和说明:
ES6新添加的接口 语法:Object.assign(target,source1,source2,source3); 属于浅拷贝——>拷贝过来的只是一个引用 对象合并时,一旦碰到对象里同名属性,就会出现后面对象中的属性覆盖前面对象中的属性现象一般按如下方式写
var source1 = { m:'front', subm:'money_sign', action:'init', }; var source2 = { account_id:'afb12', mp_id:'3' } var obj = Object.assign({}, source1, source2); console.log(obj); // {m: "front", subm: "money_sign", action: "init", account_id: "afb12", mp_id: "3"}
为对象添加属性Object.assign 是针对Object开发的API,不仅实现简单的多个对象的合并,还可以为对象添加属性、方法等
这里写代码片为对象添加方法
function sometest (){ } // 方法也是对象 // 将两个方法添加到类的原型对象上 // 类的实例会有这两个方法 Object.assign(sometest.prototype,{ test1(arg1,arg2){ console.log('this is method one='+arg1); console.log('this is method one='+arg2); }, test2(){ console.log('this is method two'); } }); sometest.prototype.test1('haode','2') sometest.prototype.test2() console.log(sometest.prototype) 结果: this is method one=haode this is method one=2 this is method two {test1: , test2: , constructor: } test1: test1(arg1, arg2) test2: test2() constructor: sometest()__proto__: Object Object() { [native code] }