This of JavaScript

Source: Internet
Author: User
Tags event listener

In a nutshell: This in the JavaScript function always points to the direct object that called the function. Of course through apply (), call (), bind () These methods can change this except

Instance 1:alert (this = = = window); True the direct object calling the function is the global window

Instance 2:var test = function () {alert (this = = window)}; Test (); True the direct object calling the function is still the global window

Instance 3:var test = function () {alert (this = = window)}; New test (); False because the New keyword creates an empty object, which is equivalent to a direct object called by the empty object as a constructor, this does not point to the window but points to the empty object and initializes the empty object as the return value.

Instance 4:var test = {' A ': 1, ' B ': function () {alert (this = = Test);}}; TEST.B ()//true This is the direct object that test is called as a function test.b

Instance 5:var test = {' A ': 1, ' B ': {' B1 ': function () {alert (this = = = test.b);}};  TEST.B.B1 (); True when test.b as a direct object called by the function test.b.b1

Instance 6:var test = function () {var inner = function () {alert (this = = window);} inner ();};  Test (); True similar to this in the closure function, no matter how many layers, the direct object of the calling function is always the global window

Example 7: About the prototype chain inheritance var test = function () {}; var test2 = function () {THIS.A = function () {alert (this = = = p1);}}; var P2 = new Test2 (); Test.prototype = p2; Test.prototype.constructor = Test;var P1 = new Test (); P1.a (); True at this point P1 as a direct object called by the function p2.a

Instance 8:dom node Event listener function <div onclick= "SHW (This)" ></div> the This at this point points to the node element object

This of JavaScript

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.