< input id="btnTest" type="button" value="Button"/>
",
handlerFun:function(){ document.getElementById('btnTest').onclick=handler.handlerFun ;
program. 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 Copy the code
The code is as follows:
document.getElementById('btnTest').onclick=function(){
handler.handlerFun(); document. The onclick program uses a closure 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
Copy code
The code is as follows:
function bind (fn,context){
document.getElementById('btnTest') .onclick=bind(handler.handlerFun,handler);The function can be bound to the specified environment through the customized bind function. The bind() function receives two parameters: a binding function, An execution environment and returns a function that calls the bound function in the execution environment. 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.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn