簡體   English   中英

有人可以向我解釋這小段JavaScript代碼嗎?

[英]Can someone explain this small piece of javascript code to me?

基本上,我希望console.log輸出“是”,但不會。 我可以做些什么使它輸出yeah而不直接在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();

usefulFunction ,您期望按引用傳遞的C ++樣式會影響對config.updateThis的原始引用,但是,當您調用

 this.usefulFunction(this.config.updateThis);

您正在創建對'false'字符串的新引用(以傳遞給usefulFunction ),並且您無法從usefulFunction更新this.config的原始引用。

解決此問題的唯一方法是傳遞對象名稱以進行更新。 同樣,JS中沒有C ++通過引用傳遞。 工作實例

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}

您可以將一個對象(與字符串對象相對)傳遞給函數。 這樣做的原因是因為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;
}

假設您的代碼實際可行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM