Q1 Why did the console output two undiffed at the end?
var a = {
b: {
m: function() {
console.log(this.p);
},
p: 'Hello'
}
};
var hello = a.b.m;
hello()
Q2 feels like there is one more undiffed
//代码
var a = {
b: {
m: function() {
console.log(this.p);
},
p: 'Hello'
}
};
var hello = a.b;
hello.m();
Supplement:
Source of the problem:
This keyword in Ruan Yifeng’s JS standard
The above code is in the link, 2. (3) Object method The last paragraph
Automatically answer, summarizing previous help:
Q1
The first one is undefined, because hello points to a method, which can be seen as functionName, so this is window
this.p; //window.p
//First declare a window.p, no value is assigned, the value is undiffedThe key is that there is one more undiffed!
Q2The second undefined has an arrow in front of it.
Add a return 'test' in the m function.
//"test"
So, this arrow can be regarded as the value after return. Here, the m function has no return. If there is no return value, it is undiffed
Summary: The previous arrow is unique to the console. It is not available during command line debugging. The console first executes the function, and then outputs the execution result of the function (for example, it can be used to assign values to other things)
The first one is undefined, because hello points to an object, which can be regarded as b, so
is the return value of the last statement. Can you try adding a return "test" to the m function?
Personally, I think the first undefined is because the function has no return value, and the second undefined may be due to browser debugging. Can you try using command line debugging to see if the second undefined appears.
Are you using the Chrome browser console? The second undefined is inherent and has nothing to do with your code.
Enter var a = 1;
There is also undefined when pressing Enter.
I think it’s you. The this pointer of this method has changed the definition of the method in the a object to a variable under window. At this time, this points to window. There is no definition of p under window. You can declare one before var hello. var P will understand
1.hello() has no return value
2.console.log() This function has no return value
Extra questions
undefined
是js语句本身的值,剩下的就是this
.