如果在外面打电话,功能不会起作用

时间:2017-03-15 18:47:53

标签: javascript

如果我在函数外部调用console.log(window.Test),函数不起作用并且我得到了未定义。

当我在下面的代码中调用函数内部时工作 -

var num = 0;
function clientseed() {

var a = "test";
num++;

window.Test = a + "-" + num;

console.log(window.Test)
}

但不是下面的那个---即使我正在使用窗口。这是用于定义全局变量,但我得到未定义的结果..如果我单击按钮3次并转到控制台并输入console.log(window.Test)它也显示undefined

var num = 0;
function clientseed() {

var a = "test";
num++;

window.Test = a + "-" + num;

}

console.log(window.Test)

HTML

<button onclick="clientseed()">Test</button>

2 个答案:

答案 0 :(得分:1)

  

即使我正在使用窗口。这是用于定义全局变量,但我得到未定义的结果..

您正在使用window,这很好但是,甚至在您声明变量之前,您的日志语句已被执行。

案例1(热门代码段):

Button click {

 // declared the variable
 // printed.

}

案例2:

Button click {

 // declared the variable

}

// printed.  -- well the button not yet clicked. I don't know what is the variable you are asking me to print.

答案 1 :(得分:1)

window.Test未定义。您超出了范围,这意味着您要在尚未调用的函数中定义全局变量。 Test尚不存在。这就是为什么当你致电console.log(window.Test)时,你会得到undefined

您可以执行的操作是在设置变量console.log后移动Test

<强> E.g。

function clientseed() {
   // window.Test gets defined 
}

console.log(window.Test); // outputs undefined because clientseed() was never executed which sets the definition for Test

当您点击button时,会触发clientseed()来调用。您要完成该功能中的每个命令,直到您设置window.Test = a + "-" + num;的结尾。 NOW变量Test存在于window的范围内。调用clientseed()时,它不会再次执行console.log(window.Test)。原因是,它超出了该功能的范围。该函数仅clientseed()仅关注自身以及担心执行{}中包含的内容。

因此,如果您在点击console后查看button 3 times,则会注意undefined仅显示一次。这正是上面的那一点。页面加载后,它将调用console.log(window.Test)。在执行之前,它不会执行clientseed()。因此,Test中的window不存在。

我希望这能提供一些清晰度。

相关问题