The use of call (), apply (), bind () in JavaScript is finally understood

Source: Internet
Author: User

In fact is a very simple thing, seriously watch 10 minutes from a face to the full understanding of the B!

Let's look at the following:

  Example 1

Obj.objage; 17

Obj.myfun ()//Xiao Zhang age undefined

  Example 2
 

Shows ()//Blind Monk

Compare the difference between this, the first this point to obj, and the second globally declared shows () function this is the window;

1,call (), apply (), bind () are used to redefine this object!

Such as:

  

Obj.myFun.call (db);//Delmar Age 99

Obj.myFun.apply (DB); Delmar Age 99

Obj.myFun.bind (DB) (); Delmar Age 99

Above the bind method after more than one (), the results return are consistent! As a result, Bing returns a new function that you must invoke before it is executed 2, compared to call, bind, and apply parameters
    

Obj.myFun.call (db, ' Chengdu ', ' Shanghai ');//Delmar Age 99来 from Chengdu to Shanghai

Obj.myFun.apply (db,[' Chengdu ', ' Shanghai '); Delmar age 99来 from Chengdu to Shanghai

Obj.myFun.bind (db, ' Chengdu ', ' Shanghai ') (); Delmar age 99来 from Chengdu to Shanghai

Obj.myFun.bind (db,[' Chengdu ', ' Shanghai ') (); Delmar age 99来 from Chengdu, Shanghai to undefined

  

The subtle gap! From the above four results it is not difficult to see that call, bind, apply the first parameter of the three function is the object of this, the second parameter difference comes: Call parameters are directly put in, the second third nth parameters are separated by commas, directly into the back Obj.myfu    N.call (db, ' Chengdu ', ..., ' string '); all parameters of apply must be placed inside an array obj.myFun.apply (db,[' Chengdu ', ..., ' string ');        Bind except that it returns a function, its parameters are the same as call. Of course, the parameters of the three are not qualified to be a string type, allowing for various types, including functions, object, and so on!

The use of call (), apply (), bind () in JavaScript is finally understood

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.