Three tips in JavaScript functions "three"

Source: Internet
Author: User
Tags closure

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"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.