The binding of this in JavaScript

Source: Internet
Author: User

There are many ways to bind this in JavaScript, which is summarized in the recent learning process, with default bindings, implicit bindings, display bindings, forced bindings, and instance bindings.

Next we look at:

Default bindings:

The code is as follows:

function foo () {

Console.log (THIS.A);

}

var a = 3;

Foo (); 3

Under global scope This is specified by default to window, and the default binding is how the call location determines the bound object of this.

Implicit binding:

function foo () {

Console.log (THIS.A);

}

var obj = {a:3, foo:foo};

Obj.foo (); 3

Implicit binding is easy to lose, such as

var Bar=obj.foo;

Bar ();//undefined

The call location is under window but the Foo method specifies obj as its binding object

Show Bindings:

function foo () {

Console.log (THIS.A);

}

var obj = {A:3};

Foo.call (obj); 3

Force this to be bound to obj when we invoke foo using call

Force binding:

function foo () {

Console.log (THIS.A);

}

var obj = {A:3};

var bar = function () {

Foo.call (obj);//Forced binding

};

Bar (); 3

SetTimeout (bar, 100); 3

A bar that is forced to bind can no longer modify its this

Bar.call (window); or 3?

Instance bindings:

JavaScript also has a new operator

function foo (a) {

THIS.A = A;

}

var bar = new Foo (3);

Console.log (BAR.A); 3

The binding of this in JavaScript

Related Article

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.