javascript - 求解js 的問(wèn)題 為什么結(jié)果是5? 分析一下
問(wèn)題描述
<!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>
問(wèn)題解答
回答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)// 實(shí)際上 argA 就等于 1,** 這個(gè)地方的 b 沒(méi)有被用到 **
則原式簡(jiǎn)化成:
let test = functionA(argA)
此句執(zhí)行完后 test 實(shí)為
function (b) { return this.a + b}// ** 這是一個(gè)帶一個(gè)參數(shù)的函數(shù),執(zhí)行 test(4) 時(shí) b 就是 4 **
且此時(shí) 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這個(gè)變量,test其實(shí)就是一個(gè)函數(shù),如下
var test = function(b){ return this.a + b;}
外面那層部分是一個(gè)立即執(zhí)行的函數(shù),首先,
function(a,b){ return a; }(1,2)
這部分的結(jié)果就是 1,也就是說(shuō),代碼可以簡(jiǎn)化為:
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. javascript - sublime快鍵鍵問(wèn)題2. javascript - immutable配合react提升性能?3. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽(tīng)數(shù)據(jù)變化4. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語(yǔ)法錯(cuò)誤5. css - 寫頁(yè)面遇到個(gè)布局問(wèn)題,求大佬們幫解答,在線等,急!~6. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問(wèn)7. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?8. phpstudy8.1支持win11系統(tǒng)嗎?9. 實(shí)現(xiàn)bing搜索工具urlAPI提交10. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問(wèn)?

網(wǎng)公網(wǎng)安備