The difference between the call apply method in JavaScript

Source: Internet
Author: User

function foo (arg1, arg2, Arg3) {

Alert (Art1 + arg2 + arg3);

}



Foo.call (this, arg1,arg2,arg3) = = Foo.apply (this, arguments) = = This.foo (arg1, arg2, Arg3)


Call, Apply is a method of Function.prototype, which is implemented internally by the JavaScript engine because it belongs to Function.prototype

So every instance of a function object, that is, each method has a call, apply property.

Two methods are easy to confuse, because they work the same way, but only in different ways.


Same point: Two methods work exactly the same

Different points: Methods are not passed in the same way.


For Foo.call (this, arg1, arg2, Arg3)


Foo is a method, this is a method execution context-sensitive object, arg1, Arg2, ARG3 is the parameter passed to the Foo method. Here the so-called method executes when the context-sensitive object, if there is an object-oriented The basics of programming, which is well understood, is the this in the object after the class is instantiated.

In JavaScript, the code always has a context object, and the code processes the object within it. The context object is represented by the this variable, which always points to the object in which the current code is located.


Below an example, understand!

<script type= "Text/javascript" >function print (ARG1,ARG2,ARG3) {alert (arg1 + '-' +arg2+ '-' + arg3 ')}function Exampl E (A, B, c) {//call mode print.call (this,a,b,c);//apply method, the parameter is passed as an array, you can directly use the arguments array print.apply (this, which is within the JavaScript method itself) arguments);//package Array print.apply (This,[a,b,c]);} </script><input type= "button" value= "test" onclick= "Example (' Wang ', ' Ting ', ' tttt ')"/>


Popped up 3 times




The difference between the call apply method in JavaScript

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.