JavaScript Call and apply

Source: Internet
Author: User

Use:

Each function contains two non-inherited methods: Call and apply. Their purpose is to invoke the function in a particular scope, which is actually equivalent to setting the value of this in the function body.

Statement block: Fn.call (Obj,arg1,arg2,arg3 ...) Fn.apply (obj,[arry]/arguments)

The most powerful place for call and apply is the ability to expand the scope in which functions are run, the actual scenario being as follows:

varName ="Repetition Machine", Age= -; function say () {Console.log ("Name:"+ This. Name); Console.log ("Age :"+ This. age);}varobj ={name:"BB Machine", Age: -}say (); //Name: Repetition machine age:25Say.call (obj);//NAME:BB Machine age:30

If we don't use the call method, how do we invoke the say function with obj?

varName ="Repetition Machine", Age= -; function say () {Console.log ("Name:"+ This. Name); Console.log ("Age :"+ This. age);}varobj ={name:"BB Machine", Age: -}say (); //Name: Repetition machine age:25Obj.say =Say;obj.say ();//NAME:BB Machine age:30

You can see that using call will be more convenient!

JavaScript Call and apply

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.