gpt4 book ai didi

JavaScript如何通过引用的var将新函数分配给原始变量

转载 作者:行者123 更新时间:2023-11-28 02:36:33 25 4
gpt4 key购买 nike

我正在尝试通过另一个引用变量将新函数分配给 javascript 中的变量。我有以下代码:

grp0 =
{
"grp0_0":
{
"grp0_0_0": function()
{
console.log('test', 0, 0, 0);
},

"grp0_0_1": function()
{
console.log('test', 0, 0, 0);
}
},

"grp0_1":
{
"grp0_1_0": function()
{
console.log('test', 0, 1, 0);
},

"grp0_1_1":
{
"grp0_1_1_0": function()
{
console.log('test', 0, 1, 1, 0);
},

"grp0_1_1_1": function()
{
console.log('test', 0, 1, 1, 1);
}
}
},

"grp0_2": function()
{
console.log('test', 0, 2);
}
}

function replaceFunc(group, names)
{
if (typeof group === 'function')
{
console.log('replace function:', names);
group = function()
{
console.log('something else');
}
}
else
{
$.each(group, function(name, value)
{
replaceFunc(value, names.concat(name));
});
}
}

grp0.grp0_1.grp0_1_0();

replaceFunc(grp0, []);

grp0.grp0_1.grp0_1_0();

正如预期的那样,输出:

test 0 1 0
replace function: ["grp0_0", "grp0_0_0"]
replace function: ["grp0_0", "grp0_0_1"]
replace function: ["grp0_1", "grp0_1_0"]
replace function: ["grp0_1", "grp0_1_1", "grp0_1_1_0"]
replace function: ["grp0_1", "grp0_1_1", "grp0_1_1_1"]
replace function: ["grp0_2"]
test 0 1 0

但我希望最后一行是:

something else

如何更改原来的功能?

感谢您的帮助。

最佳答案

Javascript 函数参数始终按值传递,而不是按引用传递。这意味着虽然您可以更改参数的值,但更改不会反射(reflect)在调用方。

function test(a) {
a = 'd';
}

var b = 'c';
test(b);
console.log(b);
// 'c'; <<= the value has NOT been changed

当将对象作为参数传递给函数时,它实际上是对所传递对象的引用。然而,引用本身仍然被复制。这意味着虽然您无法替换对象本身,但您可以更改其属性。

因此,如果您想更改函数内的值,则必须传递一个对象;对该对象属性的任何更改都将对调用函数可见。

function test(p) {
p.a = 'd';
}

var o = {a: 'c'};
test(o);
console.log(o.a);
// 'd'; <<= the property's value HAS been changed

关于JavaScript如何通过引用的var将新函数分配给原始变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396932/

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