javascript - 求解js 的問題 為什么結果是5? 分析一下
問題描述
<!doctype html><html lang='zh-CN'><head><meta http-equiv='X-UA-Compatible' content='IE=edge'/><meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'><meta charset='UTF-8'/><title>Document</title></head><body><script> var test=(function(a){ this.a=a; return function(b){ return this.a+b; } }(function(a,b){ return a; debugger; }(1,2))); console.log(test(4)) //結果是輸出5 求解? </script></body></html>
問題解答
回答1:記
let functionA = function (a) { this.a = a return function (b) {return this.a + b }}let argA = function (a, b) { return a debugger}(1, 2)// 實際上 argA 就等于 1,** 這個地方的 b 沒有被用到 **
則原式簡化成:
let test = functionA(argA)
此句執行完后 test 實為
function (b) { return this.a + b}// ** 這是一個帶一個參數的函數,執行 test(4) 時 b 就是 4 **
且此時 this.a 等于 1。因此 test(4) 結果為 5
回答2:很顯然是5啊
var test = function(a){ this.a = a; return function(b){return this.a + b; } }(function(a,b){ return a; }(1,2))
分解
var test = function(a){ this.a = a; return function(b){return this.a + b; } }var getA = function(a,b){ return a; }test(getA(1,2))(4);
這要再看不懂,你就要好好學習下基礎了
回答3:首先我們要理解test這個變量,test其實就是一個函數,如下
var test = function(b){ return this.a + b;}
外面那層部分是一個立即執行的函數,首先,
function(a,b){ return a; }(1,2)
這部分的結果就是 1,也就是說,代碼可以簡化為:
var test=(function(a){ this.a=a; return function(b){ return this.a+b; } }(1));
在上面的代碼里面,a=1,因此,在test(4)中,我們得到的是:
var test=(function(a){ // a = 1 this.a=a; return function(b){ // b = 4 return this.a+b; // 得到 1 + 4 } }(1));
相關文章:
1. Python中使用超長的List導致內存占用過大2. 谷歌訪問助手安裝不了3. javascript - sublime快鍵鍵問題4. css - PC端不同分辨率下字體大小呈現5. css - input中transition 設置background-color過渡,chrome瀏覽器頁面初始化渲染會有過度效果6. javascript - JS中如何實現 DIV內部和鼠標的距離7. pdo - mysql 簡單注入疑問8. python判斷字符串相等?9. javascript - 怎么獲取一個頁面中的所數據,然后弄成一個json格式的字符串傳給后臺10. html5 - 在一個頁面中 初始了兩個swiper 不知道哪里錯了 一直不對
