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