A simple function binding
Function binding is often used when JavaScript interacts with DOM. Define a function and then bind it to an event trigger of a specific DOM element or collection. The binding function is often combined with a callback function Used with event handlers to pass functions as variables while preserving the code execution environment.
The above example creates a handler object, and the handler.handlerFun() method is assigned as the click event handler of the DOM button. The design intention is this: when the button is clicked, this method is triggered, and a dialog box pops up to display the message defined by the handler. However, the content of the dialog box is undefined after clicking. Students who are familiar with closures can easily see that the problem is that the execution environment of the handler.handlerFun() method is not saved. The this object finally points to the DOM button instead of the handler. You can use closures to solve this problem. Modify the function binding statement
document.getElementById('btnTest').onclick=function(){
using ‐ to use closure ‐ ‐ ‐ ‐ ’ ’ s ’ ’ s } } } } The solution is to use a closure inside the onclick program to directly call the handler.handlerFun() method. Of course, this is a solution specific to this scenario. Creating multiple closures may make the code difficult to understand and debug.
Custom bind function
function bind(fn,context){
.
}
onclick=bind(handler.handlerFun,handler); The function can be bound to the specified environment through the custom bind function. The bind() function receives two parameters: a binding function, an execution environment, and returns an execution environment A function that calls the bound function. It looks simple, but its function is very powerful. A closure is created in bing(). The closure uses apply() to call the passed function, and passes the execution environment and parameters to apply(). The arguments here are Internal anonymous function, not bind(). When the returned function is called, it executes the passed function in the given function, given all arguments. In the above example, calling handler.handlerFun can still get the parameter event, because all parameters are passed to it through the bound function.
Summary
Once a function is passed in the form of a function pointer, and the function must be executed in a specific environment, the custom bind() function can be used. They are mainly used for event handlers and setTimeout and setInterval , However, this binding method requires more memory overhead than ordinary functions, so try to use it only when necessary.