Call and apply

Source: Internet
Author: User
Call and apply

 

Call and apply can be used to redefine the execution environment of the function, that is, the point of this, which is very common for some applications.

 

Call () methodExample:

 

Function Changestyle (type, value ){

This. Style [type]=Value;

}

VaROBJ=Document. getelementbyid ('Div1');

Changestyle. Call (OBJ,'Fontsize','20px');

Changestyle ('Fontsize','30px');//Error. In changestyle, This references the window object.

Note that the changestyle. Call () method has three parameters.

The first parameter is used to specify The object to which the function is called. O is specified here. BJ , Which means that the changestyle function will be BJ Therefore, this point in the function body is o BJ Object. The second and third parameters correspond to the type and value parameters in the changestyle function. Final The result we see is the DOM element O. BJ The font of is 20 PX.

 

Apply () methodExample:

 

VaR OBJ = Document. getelementbyid ( ' Div1 ' );

Changestyle. Apply (OBJ ,['Fontsize','20px']);

Changestyle ('Fontsize','30px');//Error. In changestyle, This references the window object.

 

The usage of "Apply" is roughly the same as that of "call". There is only one difference. "Apply" only accepts two parameters. The first parameter is the same as "call,The second parameter must beArrayThe elements in the array correspond to the form parameters of the function.

 

Content from blog

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.