Use of Call and Applay

Source: Internet
Author: User

    1. Call method
    • Invokes one method of an object, replacing the current object with another object. To be clear, it is to change the object's internal pointer, that is, to change the object's pointer to the content, the reference code is as follows:

function Obj () {
This.value= "The variable of obj";
} var value= "the window"; function fn () {
alert (this.value);
} Window.fn (); The Window fn.call (window); The Window fn.call (New OBJ ()); Variables for obj

 

var fun = new function () {   this.a= ' fun ';} var  myfun =function (x) {   var a = "Myfun";   Alert (THIS.A), alert (x)}myfun.call (fun, ' var ')//fun   

  

Finally, the analysis results

1. The Global Object window call function Fn,this points to the Window object, so this.value is the window

2, the function FN calls the call method, this defaults to the first parameter window object, so this.value also for the window

3. The function FN calls the call method, this defaults to the first parameter, new obj (), which is the Obj object, so this.value is the variable of the member variable obj of obj

5, Function Myfun Call method, this default point to the first parameter fun function object, so This.value is THIS.A, that is fun

6, the function Myfun call method, the second parameter is the function object Myfun parameter, so alert (x) is the second parameter Var

Both call and apply are the same in effect. But the two are different on the parameters. For the first argument all the same, but for the second argument, apply passes in an array of arguments, which means that multiple parameters are passed into an array, and call is passed in as a parameter to call:

Fun.call (FUN1,VAR1,VAR2,VAR3)

Fun.apply (Fun1,[var1,var2,var3])

Use of Call and Applay

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.