Functions in JavaScript: apply, call, and length attributes of functions

Source: Internet
Author: User

Apply, call, and length attributes of the Function
JavaScript defines two methods for function objects: apply and call. They are used to bind the function to another object for running. The two methods are different only when defining parameters:

Function. prototype. apply (thisArg, argArray );
Function. prototype. call (thisArg [, arg1 [, arg2…]);

 

From the function prototype, we can see that the first parameter is named thisArg, that is, the this pointer inside all functions will be assigned thisArg, this achieves the purpose of running a function as another object. The two methods except the thisArg parameter are the parameters passed for the Function object. The following code illustrates how the apply and call methods work:

// Define A function func1 with the property p and method
Function func1 (){
This. p = "func1 -";
This. A = function (arg ){
Alert (this. p + arg );
}
}
// Define a function func2 with the property p and method B
Function func2 (){
This. p = "func2 -";
This. B = function (arg ){
Alert (this. p + arg );
}
}
Var obj1 = new func1 ();
Var obj2 = new func2 ();
Obj1.A ("byA"); // display func1-byA
Obj2. B ("byB"); // display func2-byB
Obj1.A. apply (obj2, ["byA"]); // display the func2-byA, where ["byA"] is an array with only one element, the same below
Obj2. B. apply (obj1, ["byB"]); // display func1-byB
Obj1.A. call (obj2, "byA"); // display func2-byA
Obj2. B. call (obj1, "byB"); // display func1-byB

It can be seen that after method A of obj1 is bound to obj2 for running, the runtime environment of function A is transferred to obj2, that is, this Pointer Points to obj2. Similarly, function B of obj2 can be bound to the obj1 object for running. The last four lines of the Code show the differences between the parameters of the apply and call functions.

 

 

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.