Let's say I have a nested function named countries and I want to call two functions with one named Russia with parameter named cities1 and another named China with parameter named cities2 within the function countries. How do I call the two functions with parameters within a nested function?
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;
}
I think you can use an Object (like a Class).
What about the code below?
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>
But if you really want to call nested funcions you could use closures:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.