gpt4 book ai didi

javascript - 分配给在 ES5 中作为参数传递的对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:12:11 24 4
gpt4 key购买 nike

我有一个对象作为参数传递给函数。在该函数内部,我想为其分配一个不同的值,但是因为在该函数内部我们仅引用原始对象,所以我们不能使用 = 进行简单赋值。

在 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);

最佳答案

Is there a workaround I could use in ES5, other than copying properties to the reference?

实际上,Object.assign 也只是复制属性。但是你可以简单地使用 polyfill并在 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;
};
}

关于javascript - 分配给在 ES5 中作为参数传递的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41746946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com