dan*_*cek 3 javascript ecmascript-5
我有一个对象,我作为参数传递给函数.在该函数内部我想为它赋予一个不同的值,但是因为在函数内部我们只引用了原始对象,所以我们不能使用简单赋值=.
在ES2015中,我可以使用Object.assign
除了将属性复制到引用之外,是否有我可以在ES5中使用的解决方法?
以下是https://jsbin.com/wimuvaqosi/1/edit?js,console的示例
var x = {prop:1};
function foo(x1) {
var y = {prop:2};
x1 = y; //this obviously does not work
//x1 = Object.assign(x1, y); //this works only in ES2015
}
foo(x);
console.log("x ", x);
Run Code Online (Sandbox Code Playgroud)
除了将属性复制到引用之外,是否有我可以在ES5中使用的解决方法?
不是,Object.assign也只是复制属性.但是,你可以简单地使用填充工具 ,在你预ES2015代码中使用Object.assign():
if (typeof Object.assign != 'function') {
Object.assign = function(target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
Run Code Online (Sandbox Code Playgroud)