There is a requirement in the project, the first execution of the event is different from the subsequent execution, but the directly passed the well-defined named function returns the same result: If the named function is nested within an anonymous function, the result will be returned correctly! The code is as follows:
Code
<button class="button">按钮</button>
( function(w) { //define code blocks to be executed for the first time varfn = function() {Console.log (1); };varBTN = Document.queryselector ('. Button '); Btn.addeventlistener (' click 'Fnfalse); Btn.click ();//Overwrite the FN reference, the second code that needs to be executed laterfn = function() {Console.log (2); }; }) (window);
The above code has been printed 1
( function(w) { //define code blocks to be executed for the first time varfn = function() {Console.log (1); };varBTN = Document.queryselector ('. Button '); Btn.addeventlistener (' click ', function() {FN (); },false); Btn.click ();//Overwrite the FN reference, the second code that needs to be executed laterfn = function() {Console.log (2); }; }) (window);
This code prints 1 for the first time, then click Print 2
Here you need to understand concepts: object reference types and function closures
Interpretation
Objects are passed by reference. The first FN points to an anonymous function (object), and then adds an event that points to an anonymous function (object), and you overwrite FN without overwriting the anonymous function (the object); The second event is an anonymous function that calls the function that FN points to (to form a closure that takes the last assigned FN).
var a = b = c = {d:1//a, b同指向一个对象//改写b指向另一个对象3//改写c指向对象的参数//Object{c:3},因为a, c指向同一对象,引用传递不是复制,这个例子中的b就好比fn
Postscript
At the beginning of the project to implement this feature is the first method, but not implemented, with colleagues pointing, need to nest an anonymous function, to form a closure, take the last assignment of FN. The reference type of the object is familiar before, but the understanding is not profound, the specific problem cannot be analyzed. So the basics still have to be understood thoroughly.
The difference between passing anonymous functions (nested defined named functions) and named functions in JavaScript event snooping