[英]Javascript function inside a function — confused about arguments
Hi everyone, I'm in the process of learning Javascript and I'm confused about having a function inside another function, in particular the argument part. 大家好,我正在学习Javascript,并且对在另一个函数(尤其是参数部分)中包含一个函数感到困惑。
I've included a sample code from the lesson where it's looking to calculate the years until retirement for three people given their year of birth. 我在本课程中提供了一个示例代码,该代码旨在计算给定出生年限的三个人退休之前的年龄。
What I'm confused about is the year within the function yearUntilRetirement(name, year ). 我感到困惑的是函数yearUntilRetirement(姓名, 一年 )内的年份 。
Shouldn't this be yearOfBirth instead of year since it's looking back at the calculateAge(yearOfBirth) function to find the age? 这是不是应该回溯年份而不是年份,因为它会回头calculateAge(yearOfBirth)函数来查找年龄? Or is this argument only unique to the function it is currently in?
还是此参数仅是当前函数唯一的?
function calculateAge(yearOfBirth) {
var age = 2016 - yearOfBirth;
return age;
}
function yearsUntilRetirement(name, year) {
var age = calculateAge(year);
var retirement = 65 - age;
console.log(name + ' retires in ' + retirement + ' years.');
}
yearsUntilRetirement('John', 1990);
yearsUntilRetirement('Mike', 1969);
yearsUntilRetirement('Mary', 1948);
Maybe this will clarify. 也许这会澄清。
When you call yearsUntilRetirement(name, year)
, you pass in two values as the arguments. 调用
yearsUntilRetirement(name, year)
,您传入两个值作为参数。 Such as yearsUntilRetirement("John", 1975)
. 如
yearsUntilRetirement("John", 1975)
。 Then, inside of the function yearsUntilRetirement
, the other function calculateAge
is called, using the value of year
as the argument. 然后,在
yearsUntilRetirement
函数内部,使用year
的值作为参数调用另一个函数calculateAge
。 Since year
is the value 1975
, we get age = calculateAge(1975)
. 由于
year
是1975
year
的值,因此我们得到age = calculateAge(1975)
。 Now, within the calculateAge
function, the value 1975
is the value corresponding to yearOfBirth
. 现在,在
calculateAge
函数中,值1975
是对应于yearOfBirth
的值。 So, running everything through, you get var age = 2016 - 1975
. 因此,贯穿一切,您将获得
var age = 2016 - 1975
。
If this is too drawn out, I will attempt to clarify further. 如果过于草率,我将尝试进一步澄清。 Drop a comment if you need anything else.
如果您还有其他需要,请发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.