iT邦幫忙

0

關於JavaScript function問題

  • 分享至 

  • xImage

如下程式碼
我想了解為什麼最後的
app.map.test();
輸出不是 new

const app = {
    map: {},
    on(key, callback) {
        this.map[key] = function (params) {
            callback(params);
        };
    },
};
let testFn = function(params){
    console.log("old");
}
app.on("test", testFn);
console.log(app.map.test);//f(params){callback(params)};

app.map.test();    //output: old

testFn = function(event){
    console.log("new");
}
app.map.test();    //output: old
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
neil_0221
iT邦新手 5 級 ‧ 2022-09-01 15:44:50
最佳解答

app.on 建立時形成閉包
可參考:https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Closures

const app = {
  map: {},
  on(key, callback) {
 
      this.map[key] = function (params) {
        console.log(callback);   //ƒ (params){console.log("old");}
          callback(params);
      };
  },
};
let testFn = function(params){
  console.log("old");
}
app.on("test", testFn);
console.log(app.map.test);//f(params){callback(params)};

app.map.test();    //output: old

testFn = function(event){
  console.log("new");
}
app.map.test();   
Season iT邦研究生 4 級 ‧ 2022-09-01 17:52:53 檢舉

謝謝回答 我在看到閉包時就想起了這個特性

2
Felix
iT邦研究生 2 級 ‧ 2022-09-01 17:15:42

函式建立時,內外部的變數就會是當下的值或址,唯一可變的只有傳入的參數而已,這也就是 neil_0221 所說的閉包。

不完整的記憶體操作步驟如下:

let testFn = function (params) {
    console.log('test');
};
  1. 配置一記憶體空間 A 給 function
  2. 寫入 function 至 A
  3. 配置一記憶體空間 B 給 testFn
  4. 寫入 A 的記憶體位址至 B(參考)
app.on('test', testFn);

// =

this.map['test'] = function (params) {
    testFn(params);
};
  1. 配置一記憶體空間 C 給 function
  2. 寫入 function 至 C
    • 此時 testFn 參考 A
  3. 配置一記憶體空間 D 給 app.map.test
  4. 寫入 C 的記憶體位址至 E(參考)
testFn = function (event) {
    console.log('new');
};
  1. 配置一記憶體空間 F 給 function
  2. 寫入 function 至 F
  3. 寫入 F 的記憶體位址至 B(參考)
Season iT邦研究生 4 級 ‧ 2022-09-01 17:54:32 檢舉

謝謝回答 我了解原因了

我要發表回答

立即登入回答