javascript中return关键字的意义 [英] Significance of return keyword in javascript
问题描述
我是javascript的新手,不介意这个问题是否显得愚蠢。当我们可以省略这个时,第三行代码中return关键字的意义是什么?
I am new to javascript, don't mind if this question seems silly. What is the significance of return keyword in third last line of code when we can omit this?
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
function makeFullName ()
{
alert( nameIntro + firstName + " " + lastName);
}
return makeFullName(); // here we can omit "return" then also it is functioning same
}
showName ("Michael", "Jackson");
推荐答案
在您的示例中,您不需要 return
因为你的函数没有产生任何对象或值,它只是做了些什么。 (它警告字符串)
In your example, you do not need return
because your function does not produce any object or value, it simply does something. (it alerts the string)
但是,假设您想要保存nameIntro字符串的值并稍后使用它。可以修改您的函数以返回值,该值可以保存为变量。以下代码将产生相同的结果,但使用 return
:
Let's say, however, that you wanted to save the value of the nameIntro string and use it later. Your function could be modified to return the value, which could be saved as a variable. The following code will produce the same results, but makes use of return
:
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
function makeFullName ()
{
return nameIntro + firstName + " " + lastName;
}
return makeFullName();
}
var nameString = showName("Michael", "Jackson");
alert(nameString);
这篇关于javascript中return关键字的意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!