javascript - 求解js 的問題 為什么結(jié)果是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)) //結(jié)果是輸出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)
此句執(zhí)行完后 test 實為
function (b) { return this.a + b}// ** 這是一個帶一個參數(shù)的函數(shù),執(zhí)行 test(4) 時 b 就是 4 **
且此時 this.a 等于 1。因此 test(4) 結(jié)果為 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);
這要再看不懂,你就要好好學(xué)習(xí)下基礎(chǔ)了
回答3:首先我們要理解test這個變量,test其實就是一個函數(shù),如下
var test = function(b){ return this.a + b;}
外面那層部分是一個立即執(zhí)行的函數(shù),首先,
function(a,b){ return a; }(1,2)
這部分的結(jié)果就是 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));
相關(guān)文章:
1. PHP單例模式2. mysql 5萬張表 導(dǎo)出成sql 不要內(nèi)容,只要結(jié)構(gòu),非常慢。如何解決啊?3. mysql - eclispe無法打開數(shù)據(jù)庫連接4. mysql - 關(guān)于數(shù)據(jù)緩存策略方面的疑惑5. 數(shù)據(jù)庫 - mysql中有沒查看數(shù)據(jù)大小的函數(shù)??6. 老師 我是一個沒有學(xué)過php語言的準(zhǔn)畢業(yè)生 我希望您能幫我一下7. mysql如何配置遠程php外網(wǎng)鏈接數(shù)據(jù)庫8. mysql如何判斷數(shù)據(jù)不存在則插入呢?9. 導(dǎo)入數(shù)據(jù)庫不成功10. mysql無法刪除字段(錯誤1091),但是對該字段設(shè)置主鍵后就可刪除,為什么?
