JS's Call/apply/bind

Source: Internet
Author: User

Test code:

var a = 1; var obj = {     = 2;  } function Test (a) {    alert (a);    Alert (this. a);  }

1.test (3);

Results: 3,1

The This in the function points to the Window object

2.test.call (thisobj,param1,param2 ...);

The point of this in the Thisobj:test function

PARAM1,PARAM2: Parameters passed to the test function

3.test.call (null,3) or Test.call (undefined,3);

The results were: 1, 3;

When thisobj is undefined or null, this in test points to the window

4.test.call (1,3), or Test.call ("a", 3) or Test.call (false,3) or Test.call ([12],3) or Test.call (function () {},3) or Test.call (/ao/g,3);

The result is: 3,undefined

At this point the value of this is 1, "a", Flase,[12],function () {},/ao/g; there is no a attribute

5.test.call (obj,3);

The result is: 3,2

6.test.apply (Thisobj,[param1,param2 ...]);

In addition to giving the test arguments in array form, the other is the same as Test.call

7.test.bind (Thisobj,param1,pamra2 ...);

Bind () returns a new function, which is a copy of test, but the inside of this is a pointer to Thisobj

Source:

function (scope) {  varthis;   return function () {      fn.apply (scope);   }}

Case:

1.

var x = +; var foo = {    x: $        }varfunction(A, b) {    Console.log (  this. x,a,b);    } Bar (up); var nBar = Bar.bind (foo,4,5); NBar ();

Bar (print out): 100,1,2;this point to Widdow;

NBar () Print out: 200,4,5;this points to Foo, and NBar saves 4, 5 to the NBar parameter list when it is created

2.

var x = +; var foo = {    x: $    }varfunction(A, b) {    Console.log (  this. x,a,b);        Console.log (arguments);} Bar (up); var nBar = Bar.bind (foo,4,5); NBar (6,7);

Nbar execution: Arguments inside Saved 4,5,6,7

3.

JS's Call/apply/bind

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.