Question about the javascript prototype chain and scope during the interview
Now the school recruitment is almost over, so I have time to summarize the problems encountered during this period. I found a lot of tests on JS scope in many pen-level questions, so I will summarize the materials.
As we all know, unlike other OOP languages, js is a weak type language and has no obvious difference in data types. another difference is its scope. This is mainly because the Inheritance Method of js is throughPrototype chain.
A) js has no block-level scope. The so-called block-level scope is the part in the if, for, and while statements. The test is as follows (Chrome browser ).
The output result is as follows:
From the results, we can see that js does not have block-level scope, and str1.
B) js only contains the function scope and global scope. The function scope is analyzed below.
The output result is as follows:
From the results, we can see that js has a function scope, so str2 is undefined outside of fun1. To understand the scope of js, we need to involve the prototype chain and analyze it briefly.
C) when the specified object or variable cannot be found in the current scope, js will search up through the prototype chain, that is, find the parent scope of the current scope. If not found, it will still search up, until it is found or the root node is not found.
The output result is as follows:
From the results, we can see that str4 can still be output in fun2, because its parent-level scope is global and the global scope contains the str4 variable.
D) there is another situation about the parent-level scope mentioned above, that is, if a function is called, that is, the parent-level scope refers to the nested function.
This is confusing. I mistakenly thought that Eric would be output, but the result is not like this. The result is as follows:
The result shows that the output is gaohui instead of Eric,At this time, the parent scope refers to the parent scope of the function definition local scope, rather than the parent scope of the function call local.
This is only a simple analysis of the js scope issues during the interview process. The issues related to the more complex js prototype chain are not described in detail. If you want to study them further, please understand, can refer to here blog http://www.cnblogs.com/wangfupeng1988/tag/%E5%8E%9F%E5%9E%8B%E9%93%BE/