JS功能:为什么这不能提醒我的问候?

时间:2015-09-19 00:53:58

标签: javascript

我很好奇为什么这不会引起我的问​​候。代码:

function myNameWelcome(userName, thought) {
  var greeting = "Welcome pardner, so your're name is " + userName + ". " + thought;
  return greeting;
}

myNameWelcome("Peter", "Shine on you crazy diamond.");

alert(greeting);

3 个答案:

答案 0 :(得分:1)

您的返回值未分配给该功能之外的任何内容。

答案 1 :(得分:1)

greeting超出了范围。它是在函数内部定义的,因此在您调用alert(greeting);的范围内不可用。解决这个问题很容易:

var greeting;
function myNameWelcome(userName, thought) {
  greeting = "Welcome pardner, so your're name is " + userName + ". " + thought;
}

myNameWelcome("Peter", "Shine on you crazy diamond.");

alert(greeting);

甚至更好:

function myNameWelcome(userName, thought) {
  return "Welcome pardner, so your're name is " + userName + ". " + thought;
}

var greeting = myNameWelcome("Peter", "Shine on you crazy diamond.");

alert(greeting);

答案 2 :(得分:0)

因为greeting本地变量,只能在 myNameWelcome中访问。它不存在于函数之外。

请参阅What is the scope of variables in JavaScript?以了解有关变量范围的更多信息。