JavaScript's This multiple scenario usage

Source: Internet
Author: User

Liu Zhixiang

Date: 2017.11.10

Reference: Nanyi's official website

This is a keyword in JavaScript and can only be used within a function. The value of this will change as the occasion differs.

1. Simple global function call, at which point this points to the Window object

function  test1 () {  this. x = 1; Alert (this//  1
var x = 1; function test2 () {alert (this//  1
var x = 1; function  this. x = 0//0

The first one is called Test1 () on behalf of the window, the second function proves that this points to the global object, and the third executes test3 (), changing the global variable x so that this is pointed to the window.

2. An object calls this function

 function  Test () {alert (this. x); }  var o == 1=//  1

Object calls this function, this at this point points to the object being changed.

3. Constructor calls

function Test () {  this. x = 1;} var New  //  1

When a new object is created with test () new, this point points to the new object. And this is not global, it just points to the new object. Doesn't have any effect on the outside.

4.apply Call

Apply () is a method of a function object that changes the calling object of a function, and its first parameter represents the changed object that called the function. Therefore, this is the first parameter.

var x = 0; function Test () {alert (this. x);} var o== 1=//0
// 1

If apply () is empty, the default global call to this function, this point to the global window, so the output global 0;

Apply (O) Changes the object calling this method, at which point this points to the O object and outputs 1.

JavaScript's This multiple scenario usage

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.