javascript - Solve js problem. Why is the result 5? Analyze it
扔个三星炸死你
扔个三星炸死你 2017-07-07 10:34:36
0
3
1054
<!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>
扔个三星炸死你
扔个三星炸死你

reply all(3)
女神的闺蜜爱上我

Memory

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 没有被用到 **

The original formula is simplified to:

let test = functionA(argA)

After this sentence is executed, test is actually

function (b) {
    return this.a + b
}
// ** 这是一个带一个参数的函数,执行 test(4) 时 b 就是 4 **

And at this time this.a is equal to 1. Therefore the result of test(4) is 5

黄舟

Obviously it’s 5

  var test = function(a){
      this.a = a;
      return function(b){
        return this.a + b;
      }
    }(function(a,b){
      return a;
      }(1,2))

Breakdown

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

If you still don’t understand this, you have to learn the basics

typecho

First we need to understand the variable test. Test is actually a function, as follows

var test = function(b){
    return this.a + b;
}

The outer part is a function that is executed immediately. First,

function(a,b){
      return a;
 }(1,2)

The result of this part is 1, that is to say, the code can be simplified to:

var test=(function(a){
      this.a=a;
      return function(b){
          return this.a+b;
      }
 }(1)); 

In the above code, a=1, therefore, in test(4), we get:

var test=(function(a){ // a = 1
      this.a=a;
      return function(b){ // b = 4
          return this.a+b; // 得到 1 + 4
      }
 }(1)); 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template