This keyword is very common and important in JavaScript. So what does this mean?
Summarize:
1.this represents an internal object that is automatically generated when the function is run, and can only be used inside the function;
2.this always points to the object that called the function;
Here are four scenarios to discuss the use of this in detail
One: purely function calls
This is the most commonly used method of a function, which is a global call, where this represents the Globals object window
function Test () { this. x =1; Alert (this. x); Console.log (this); // } Test ();
And here's the case:
var x = 2; function Test () { this. x =1; Alert (this. x); Console.log (this); // } Test (); Console.log (x); // 1
You can prove that this in the function here refers to window.
Second: Invocation as an object method
A function can also act as a method call to an object, at which point this is the ancestor object.
function Test () { Console.log (this. x); 1 console.log (this); o } var o = {}; = 1; = test; O.M ();
Three: called as a constructor function
The so-called constructor is to generate a new object from this function. This will point to this new object
function Test (name) { this. Name= name; Console.log (this); // Test {name: "hehe"} } varnew Test ("hehe");
Four: Apply Call
Apply () is a method of a function object that changes the calling object of a function, and its first parameter is the object that is called after the function is changed.
This is worth the value of the first parameter, and if the argument is null, the default value is the global object
varx = 0; functionTest () {Console.log ( This); Console.log ( This. x); } varo = {}; O.x= 2; O.M=test; O.M ();//this.x-->2O.m.apply ();//this.x-->0 //Results: //Object {X:2} //2 //Window {...} //0
The This usage in JavaScript