This is always confusing in Javascript, can you tell the output of the following three kinds of test1 (), Test2 (), Test3 ()?
Note: The following JavaScript is in the running environment for the browser
1 This is used in global functions
var x = 1;
function Test1 () {
var x = 5;
alert (this.x);
}
function _test2 () {
This.x = 5;
alert (this.x);
}
2 This is used in the constructor in new
function Test2 () {
var f = new _test2 ();
}
3 This is used in methods of the object
function _test3 () {
Alert (this.x)
}
function Test3 () {
var a = {};
a.x = 100;
A.show = _test3;
A.show ();
}
Figuring out the key to this point is:
function is used in different situations, this the value will change. But there is a general principle, that is , this refers to the object that called the function.
- Test1 Call Scenario: equivalent to Window.test1 (), alert shows the value of the calling function X, which is window.x
- Test2 the called scene: when the new keyword is generated, the object that this point refers to is the newly generated object _test2 ().
- TEST3 Invocation Scenario: The function acts as a method call to an object, and this refers to the ancestor object, which is a
Do you understand the object in Javascript that this is pointing to?