javascript - JS-Problem lösen. Warum ist das Ergebnis 5?
扔个三星炸死你
扔个三星炸死你 2017-07-07 10:34:36
0
3
1023
<!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>
扔个三星炸死你
扔个三星炸死你

Antworte allen(3)
女神的闺蜜爱上我

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

黄舟

很显然是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);

这要再看不懂,你就要好好学习下基础了

typecho

首先我们要理解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)); 
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!