The code information comes from http://ejohn.org/apps/learn/.
What happens when we bind a click event of an object to an event-triggering element?
<ulID= "Results"></ul><Script>varButton={click:function(){ This. Clicked= true; } }; varElem=Document.createelement ("Li"); Elem.innerhtml= "Click me!"; Elem.onclick=Button.Click; document.getElementById ("Results"). appendchild (Elem); Elem.onclick (); Console.log (elem.clicked,"The clicked property is set above the clicked element." );</Script>
Because Elem.onclick (), when the onclick is called, this points to the object that called it, which is elem, so an error occurs.
We need to fix the context as the original object
functionbind (context, name) {return function(){ returncontext[name].apply (context, arguments); }; } varButton ={click:function(){ This. clicked =true; } }; varElem = document.createelement ("li"); Elem.innerhtml= "click me!"; Elem.onclick= Bind (Button, "click"); document.getElementById ("Results"). appendchild (Elem); Elem.onclick (); Console.log (button.clicked,"Click Properties are set above the original object");Modify the method to fit all functions
Function.prototype.bind =function(object) {varfn = This; return function(){ returnfn.apply (object, arguments); }; }; varButton ={click:function(){ This. clicked =true; } }; varElem = document.createelement ("li"); Elem.innerhtml= "click me!"; Elem.onclick=Button.click.bind (Button); document.getElementById ("Results"). appendchild (Elem); Elem.onclick (); Console.log (button.clicked,"Click Properties are set above the original object");Final goal, taking into account the function with parameters
Function.prototype.bind =function(){ varfn = This, args = Array.prototype.slice.call (arguments), object =Args.shift (); return function(){ returnfn.apply (object, Args.concat (Array.prototype.slice.call (arguments))); }; }; varButton ={click:function(value) { This. clicked =value; } }; varElem = document.createelement ("li"); Elem.innerhtml= "click me!"; Elem.onclick= Button.click.bind (Button,false); document.getElementById ("Results"). appendchild (Elem); Elem.onclick (); Console.log (button.clicked===false, "property is set above the original object")
JavaScript advanced Knowledge Point--Specifying context implementation