The difference between the call and the Apply method in JS

Source: Internet
Author: User

I. Description of call and apply

1, Call,apply is a method of function.prototype, it is implemented within the JavaScript engine, because it belongs to the Function.prototype, each Function object instance (that is, each method) Have call,apply properties. since as a property of the method, the use of them is of course for the method, and these two methods are easy to confuse, because they work the same way, just different ways of using.

2, Syntax: Foo.call (this, arg1,arg2,arg3) = = Foo.apply (this, arguments) = = This.foo (arg1, arg2, arg3);

3, the same point: two methods produce the same effect.

4, different points: The method passed different parameters.

Second, the example code
<script type= "Text/javascript" >
function A () {
This.flag = ' A ';
This.tip = function () {
alert (This.flag);
};
}
function B () {
This.flag = ' B ';
}
var a = new A ();
var B = new B ();
A.tip.call (b);
A.tip.apply (b);
</script>

Iii. code interpretation (that is, apply and call role)

1, the instance code defines two functions A and b,a contain the flag attribute and the Tip attribute (this property assigns a function), B has a flag property.

2. Create objects A and b for A and B, respectively.

3, whether A.tip.call (b); and a.tip.apply (b); The result of the operation is a popup B.

4. from the results, you can see that call and apply both allow the B object to invoke the Tip method of the A object, and modify the current action object of this.

The difference between the call and the Apply method in JS

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.