簡體   English   中英

如何在嵌套函數內使用參數調用函數?

[英]How to call functions with parameters within a nested function?

假設我有一個名為countrys的嵌套函數,並且我想在函數國家中調用兩個函數,其中一個名為Russia,參數名為citys1,另一個名為China,參數名為citys2。 如何在嵌套函數中使用參數調用這兩個函數?

function countries() {
  function Russia(cities1) {
    var totalpop1 = cities1 * (10 ** 6);
    //each city has a population of 10^6 people
    return totalpop1;
  }

  function China(cities2) {
    var totalpop2 = cities2 * (10 ** 6);
    //each city has a population of 10^6 people
    return totalpop2;
  }
  var result = totalpop1 + totalpop2;
  return result;
}

我認為您可以使用對象(如類)。

下面的代碼呢?

 var countries = { getRussia: function(cities1) { var totalpop1 = cities1 * (10 ** 6); //each city has a population of 10^6 people return totalpop1; }, getChina: function(cities2) { var totalpop2 = cities2 * (10 ** 6); //each city has a population of 10^6 people return totalpop2; }, getTotal: function(pop1, pop2) { var result = this.getRussia(pop1) + this.getChina(pop2); return result; } } var div = document.querySelector("#result"); div.innerHTML = countries.getTotal(1, 4); 
 <div id="result"></div> 

但是,如果您真的想調用嵌套函數,則可以使用閉包:

function countries() {
    return function(cities1) {
    var totalpop1 = cities1 * (10 ** 6);

    return function(cities2) {
        var totalpop2 = cities2 * (10 ** 6);

      return totalpop1 + totalpop2;
    }
  }
}

var div = document.querySelector('#result');

div.innerHTML = countries()(1)(4);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM