a simple function to bind
interact with the DOM in JavaScript, often need to use a function to bind, define a function and then bind to a specific DOM element or collection of an event trigger, the binding function often and event handler callback functions together used so that the function passed as an argument while retaining code execution environment.
<body>
<input id="btnTest" type="button" value="Button"/>
<script type="text/javascript">
var handler={
message:"Event handled.",
handlerFun:function(){
alert(this.message);
}
};
document.getElementById('btnTest').onclick=handler.handlerFun;
</script>
</body>
above example creates a handler object, handler.handlerFun () DOM method is assigned to the button's click event handler. Design intent is this: When the click of a button to trigger the method, the pop-up dialog box displays handler defined message, but after clicking the dialog box content is undefined. The students are familiar with the closure of this problem can easily be seen that there is no save handler.handlerFun () method of the execution environment, this object is the last point of the DOM button instead of handler. You can use closures resolve this issue, modify the function binding statements
document.getElementById('btnTest').onclick=function(){
handler.handlerFun();
}
so that you can get the expected results, this solution is used internally in the onclick a closure program called directly handler.handlerFun () method, of course, this is a solution specific to this scenario, create multiple closures may cause code is difficult to understand and debug.
custom bind function
function bind(fn,context){
return function(){
return fn.apply(context,arguments);
};
}
document.getElementById('btnTest').onclick=bind(handler.handlerFun,handler);
bind function through custom functions can be bound to a specific environment, bind () function takes two parameters: a binding function, an execution environment, and returns an execution environment in the binding function of the function call. Looks very simple, but its function is very powerful, in bing () creates a closure, closures use apply () function calls incoming and gave apply () incoming execution environment and parameters, where the arguments are Internal anonymous function, rather than bind () for. When the function call returns, it will execute the given function is passed the function and all the parameters given. The above examples can still get calls handler.handlerFun parameter event, because all parameters are passed to a function by binding it.
Summary
once to a function pointer is passed to the function, and the function must be performed in a specific environment, custom bind () function can be used, they are mainly used for event handlers and the setTimeout and setInterval, However, this binding mode compared to a normal function requires more memory overhead, so try to use only when necessary.
没有评论:
发表评论