Summary of the call () and apply () Methods for function objects in JavaScript

Source: Internet
Author: User

In JavaScript, each function has a call () and an apply () method, with the following examples:

First define an Some_obj object that has a say () Method:

var some_obj={
Name: ' Ninja ',
Say:function (WHO) {
Return ' Haya ' + who + ', I am a ' + this.name;
}
};

Call Some_obj.say (' Dude ');

Output: "Haya Dude, I am a Ninja"

Create an object again

var my_obj={name: ' Scripting guru '};

We now want to call the Say () method in Some_obj as a method of My_obj itself, in which case you can try the object method in the Say () function called ()

Some_obj.say.call (my_obj, ' Dude ');

Output: "Haya Dude, I am a Scripting guru";

In addition, if we do not pass the object to the first argument of call (), or to it is null, the calling object is defaulted to the global object (see note:);

Note: This refers to the global object, which in effect modifies the object function's this value through the first parameter of call;

If you use the object method apply ();

Some_obj.say.apply (my_obj,[' Dude ');

Output: "Haya Dude, I am a Scripting guru";

Thus, apply () and call () are basically the same, the difference is the transfer of the form of parameters, apply () The Parameter form is an array;

Pass more parameters: Some_obj.someMethod.call (my_obj, ' A ', ' B ', ' C ');

Summary of the call () and apply () Methods for function objects in JavaScript

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.