The original text is as follows:
This in Javascript is really hard to understand.
The code for Baidu's front-end interview questions is as follows:
var a=5;
function test(){
a=0;
alert(a);
alert(this.a);
var a;
alert(a);
}
test();
new test();
Run it on chrome. The result is:
0
5
0
0
undefined
0
The first three results are good to explain, but I am confused about the fifth result undefined. The key is this sentence:
alert(this.a);
In my understanding, when running the new test () statement, this points to test, then this. A should be
a=0;
0 in this sentence! Why is it undefined? Please answer!
Certificate ------------------------------------------------------------------------------------------------------------------------------------------
In fact, this is quite understandable. In New Test (), this points to the object new test,
Now let's see var T = new test (); then this in test points to T, when alert (this. a), because T itself does not have the attribute "A", of course it is undefined, and the blogger understands the local variables in the function as its attributes, so I cannot figure it out. Local variables and attribute members are essentially different.
In fact, what I want to talk about here is the VaR A in test, which makes the running result of this Code quite different. In the test function, the variable A is used first and then its definition is defined, vaR A changes a to a local variable in the function. Previously, variables in the function can be defined first !!! However, it is not recommended to use this method. Directly var a = 0; why is it so awkward?
The code for Baidu's front-end interview questions is as follows:
var a=5;
function test(){
a=0;
alert(a);
alert(this.a);
var a;
alert(a);
}
test();
new test();
Run it on chrome. The result is:
0
5
0
0
undefined
0
The first three results are good to explain, but I am confused about the fifth result undefined. The key is this sentence:
alert(this.a);
In my understanding, when running the new test () statement, this points to test, then this. a should be
a=0;
0 in this sentence! Why is it undefined? Please answer!
Certificate ------------------------------------------------------------------------------------------------------------------------------------------