1

我正在尝试通过另一个引用变量将新函数分配给 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

如何更改原始功能?

感谢您的任何帮助。

4

2 回答 2

1

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

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
于 2012-11-15T13:29:36.680 回答
0

根据 Yoshi 的评论:

你不能。如果您真的想这样做,您必须将父对象传递给 replaceFunc,然后处理该对象。例如更改属性。

我将代码更改为:

function replaceFunc(group, name)
{
    if (typeof group[name] === 'undefined') return;

    if (typeof group[name] === 'function')
    {
        group[name] = function()
        {
            console.log('something else');
        }
    }
    else
    {
        $.each(group[name], function(n, v)
        {
            replaceFunc(group[name], n);
        });
    }
}

grp0.grp0_1.grp0_1_0();

var parent = { groups: grp0 };
replaceFunc(parent, 'groups');

grp0.grp0_1.grp0_1_0();

这导致:

test 0 1 0
something else

非常感谢你

于 2012-11-15T21:19:17.687 回答