有人可以向我解释这一小段javascript代码吗?

时间:2013-02-19 21:42:19

标签: javascript

基本上我希望console.log输出'是'但它没有。如果不直接在usefulFunction内部引用它,我该怎么做才能输出它?

App = {
    config: {
        updateThis: 'false'
    },
    init: function(){
        this.usefulFunction(this.config.updateThis);
        this.consoleIt();
    },
    usefulFunction: function(item){
        item = 'yeah';
        // swap the above line for the line below and it works as expected
        // this.config.updateThis = 'yeah';
    },
    consoleIt: function(){
        console.log(this.config.updateThis);
    }
}

App.init();

3 个答案:

答案 0 :(得分:2)

usefulFunction中,您期望通过引用传递的C ++样式会影响config.updateThis的原始引用,但是,当您调用

 this.usefulFunction(this.config.updateThis);

您正在创建对“false”字符串的新引用(传递给usefulFunction),并且您无法从this.config更新usefulFunction中的原始引用。

解决此问题的唯一方法是传递要更新的对象的名称。同样,JS中没有C ++传递引用。 Working example

App = {
    config: {
        updateThis: 'false'
    },
    init: function(){
        this.usefulFunction(this.config, 'updateThis');
        this.consoleIt();
    },
    usefulFunction: function(object, prop){
        object[prop] = 'yeah';
    },
    consoleIt: function(){
        console.log(this.config.updateThis);
    }
}

问题不在于字符串是不可变的

ᚗ̸̢̛͝声称问题在于字符串是不可变的;然而,问题比这更深刻。字符串是不可变的这一事实意味着您无法更改当前引用(因此更新所有其他引用),但即使它们是可变的,您也不能只设置单独的引用并影响现有引用

var a = {b:1};
function change(obj) {
    // This is assigning {c:2} to obj but not to a
    // obj and a both point to the same object, but 
    // the following statement would simple make obj point to a different object
    // In other languages, you could define function(&obj) {}
    // That would allow the following statement to do what you intended
    obj = {c:2};
}

change(a);
console.log(a); // still {b:1}

答案 1 :(得分:2)

您可以将对象(而不是字符串对象)传递给您的函数。原因是因为JavaScript字符串是不可变的。

  

原始值

     

除对象外的所有类型都定义了不可变值。具体来说,字符串是不可变的(例如,与C不同)。我们将这些类型的值称为“原始值”。这在下面的字符串部分中有更详细的解释。

     

来源:https://developer.mozilla.org/en-US/docs/JavaScript/Data_structures


如果你想将一些可变的东西传递给你的函数,那就传递一个对象。

// Calling code
this.usefulFunction(this.config);

// Useful function isn't very useful
usefulFunction: function(config) {
   config.updateThis = "some new value";
}

回到你的例子,通过函数更新配置对象。

// Calling code
this.usefulFunction("updateThis", "some new value");

// Useful function is a bit useful
usefulFunction: function(name, value) {
    this.config[name] = value;
}

答案 2 :(得分:0)

假设您的代码确实有效:

App = {
    config: {
        updateThis: 'false'
    },
    init: function(){
        this.config.updateThis=this.usefulFunction( this.config.updateThis);
        this.consoleIt();
    },
    usefulFunction: function(item){
       return item = 'yeah';
        // swap the above line for the line below and it works as expected
        // this.config.updateThis = 'yeah';
    },
    consoleIt: function(){
        console.log(this.config.updateThis);
    }
}
相关问题