Tip Three:
"Function Binding"
In JavaScript interaction with DOM, it is often necessary to use a function binding, define a function and then bind it to a specific DOM element or a collection of an event trigger, binding functions are often used with callback functions and event handlers, in order to pass the function as a variable while preserving the code execution environment
<button id= "Btn" > Buttons </button><script> var handler={ message: "Event handled." , handlerfun:function() { alert (this. message); } }; Btn.onclick = handler.handlerfun;</script>
The above code creates an object called handler. The Handler.handlerfun () method is assigned as an event handler for a Dom button. When the button is pressed, the function is called and a warning box is displayed. Although it seems that the warning box should show the event handled, the actual display is undefiend. The problem is that there is no environment to save Handler.handleclick (), so the this object finally points to the DOM button instead of the handler
You can use closures to fix this problem
<button id= "Btn" > Buttons </button><script> var handler={ message: "Event handled." , handlerfun:function() { alert (this. message); }}; Btn.onclick = function() { handler.handlerfun (); } </script>
Of course this is a solution specific to this scenario, and creating multiple closures can make the code difficult to understand and debug. A better approach is to use a function binding
A simple bind function bind () takes a function and an environment and returns a function that invokes the given function in a given environment, and passes all parameters intact.
function bind (fn,context) { return function() { return fn.apply (context,arguments);} }
This function seems simple, but its function is very powerful. A closure is created in bind (), and the closure uses apply () to invoke the passed-in function and pass the context object and arguments to apply (). When the returned function is called, it executes the passed-in function in the given environment and gives all arguments
<button id= "btn" > button </button><script> function bind (fn,context) { return function () { return fn.apply (context,arguments); }} var handler={ message: "Event handled." , handlerfun:function() {alert (this. message);}}; Btn.onclick = bind (handler.handlerfun,handler);</script>
ECMASCRIPT5 defines a native bind () method for all functions, further simplifying the operation
As long as a function pointer is passed in the form of a value, and the function must be executed in a particular environment, the utility of the bound function is highlighted. They are primarily used for event handlers as well as settimeout () and SetInterval (). However, the bound functions have more overhead than normal functions, they require more memory, and because multiple function calls are slightly slower, it is best to use only when necessary
Three tips in JavaScript functions "three"