Understanding js scope chain for one question, and js for one question
The following is a js question about the js scope chain:
function C1(name){if(name){this.name = name;}}function C2(name){this.name = name;}function C3(name){this.name = name || "John";}C1.prototype.name = "Tom";C2.prototype.name = "Tom";C3.prototype.name = "John";console.log(new C1().name + "," + new C2().name + "," + new C3().name);
Don't run. Please answer! ^ _ ^. This question is very useful for understanding js scope chain. Let's share it with you.
The most important thing to do is to understand the scope chain concept in js,
From the inside out to the outside is roughly as follows:
Local properties ---> prototype
Variable Search sequence:
What can be found in local properties will never be found in prototype
1) First, analyze the first
new C1().namefunction C1(name){if(name){this.name = name;}}C1.prototype.name = "Tom";
Analysis:
Because there is no parameter here, it is assigned as undefined by default, so if it cannot be entered here, so it is locally stored in C1
The name attribute cannot be found in the attribute, and it can only be found out because C1.prototype. name = "Tom"
Yes. The name attribute is found in prototype, so the final output is "Tom"
2). Analyze the second one.
new C2().namefunction C2(name){this.name = name;}C2.prototype.name = "Tom";
Analysis:
Because there is no parameter this time, it is also assigned as undefined by default, so the local attribute name is assigned
Undefined. As a result, the value of name is undefined,
Therefore, C2.prototype. name = "Tom" is useless. The final answer is undefined.
3). Analyze the third
new C3().namefunction C3(name){this.name = name || "John";}C3.prototype.name = "John";
Analysis:
Similarly, there is no parameter. When undefined is used as the parameter, it becomes like this:
This. name = undefined | "John", then the result is obvious that the local property name is assigned as "John ".
The next step is to search from the inside out, and the local attribute name is locked immediately. The value is "John ".
Therefore, C3.prototype. name = "John" is useless.
Final result: