简体   繁体   English

Javascript函数范围和onclick调用

[英]Javascript function scope and calling from onclick

With JavasScript, say there is an innerFunction() defined within an outerFunction() . 使用JavasScript,可以说在outerFunction()定义了一个innerFunction() outerFunction() If you attempt to call the innerFunction() , outside of the outerFunction() , there will be an error as it is not defined within the scope. 如果您尝试在outerFunction()之外调用innerFunction() ,则会出现错误,因为它未在范围内定义。
However, if while in the outerFunction() , you assign the innerFunction() to an event, say a click event, for some outside element, like a button , then the innerFunction() can be called from that scope of the button, whatever it may be. 但是,如果在outerFunction() ,你将innerFunction()分配给一个事件,比如一个click事件,对于某些外部元素,比如一个button ,那么可以从该按钮的范围调用innerFunction() ,无论如何它可能是。 So why are you able to make this second call to innerFunction() froma different scope. 那么为什么你能够在不同范围内对innerFunction()进行第二次调用。

I have a working example: http://jsfiddle.net/rcmoore38/gPrMk/ 我有一个工作的例子: http//jsfiddle.net/rcmoore38/gPrMk/

The initial changeColor() call does not work, but when changeColor() is assigned to the button , it can be called via the button. 最初的changeColor()调用不起作用,但是当将changeColor()分配给button ,可以通过按钮调用它。

Thank you! 谢谢!

There is no "scope of the button". 没有“按钮的范围”。 What happens is that you're assigning the event listener from a scope where the inner function is visible, and that's all that matters in JavaScript. 发生的事情是你从内部函数可见的作用域中分配事件监听器,这在JavaScript中很重要。 Scope in JS is about where functions are declared. JS中的范围是关于声明函数的位置。

In your example: 在你的例子中:

$("#b").click(function() { changeColor() });

the function changeColor is available via closure inside the anonymous function, because it's declared in an outer scope. 函数changeColor可以通过匿名函数内的闭包来获得,因为它是在外部作用域中声明的。 When you define a nested function, all variables and functions from the parent functions will be available inside it. 定义嵌套函数时,父函数中的所有变量和函数都将在其中可用。 So when the element is clicked and the anonymous function is called, it still has a reference to changeColor , and is able to call it. 因此,当单击该元素并调用匿名函数时,它仍然具有对changeColor的引用,并且能够调用它。

You could also set the event handler without using a closure, like this: 您也可以在不使用闭包的情况下设置事件处理程序,如下所示:

$("#b").click(changeColor);

As I said, the important thing is that changeColor is in scope when you reference it (not when it's actually called, in this case, by the browser). 正如我所说,重要的是当你引用它时, changeColor就在范围内(而不是在它被实际调用时,在这种情况下,由浏览器调用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM