Call (), apply (), bind ()

Source: Internet
Author: User

Novice: When you look at JavaScript advanced programming, you see that each function contains two non-inherited methods: Apply () and call (). A method of bind () is also added to the ECMAScript5.

The Apply () method is actually the same as the call () method, and their difference is in the way they receive the parameters. The call () method requires arguments to be passed directly to the function, and if you intend to pass directly to the arguments object or an array that is received in the containing function, use apply ().

Window.color = "Red";

var o = {color: "Blue"};

function Saycolor () {

alert (This.color);

}

Saycolor (); Red

Saycolor.call (o)//blue

The saycolor of this example is called in the global scope, so This.color is converted to window.color evaluation. In Saycolor.call (O), this points to the O object so the result is "blue".

function Add (A, b) seen on the web
{
alert (A+B);
}
function Sub (A, b)
{
Alert (A-B);
}

Add.call (sub,3,1);

The meaning of this example is to replace sub,add.call (sub,3,1) = = Add (3,1) with add, so the result is: alert (4); Note: The function in JS is actually an object, and the function name is a reference to a function object.

It should be the object sub that called the object Add method.

Call (), apply (), bind ()

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.