Today's Question:  What's your opinion about Alibaba mooncake incident?        GIVE A SHOUT

Technical Article => Web =>  JavaScript

Name resolution order in JavaScript

  sonic0002      2013-07-10 01:29:28      3,323    0    0

To understand what value a variable has in JavaScript, we need to understand some concepts such as scope and name resolution order.

JavaScript has two scopes; one is program level and the other one is function level. Unlike in C,C++ or Java, JavaScript has no block level scope. So a variable defined in a if block will still be available outside. For example, the below example:

var foo = 1;
function bar() {
	if (true) {
		var foo = 10;

The alert will display 10 since the variable foo defined in the if block can been seen by the alert() function.

Next we need to understand the name resolution. Let's first look one example:

function a (x) {
    return x * 2;
var a;

What will be the output? Will it be undefined? The answer is it will print out the function a and its body. Why? This is because in JavaScript, a name enters into the scope with following four ways:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. Variable declarations: These take the form var foo;.

The name resolution order is also the order listed above, that is function declaration comes before variable declaration. Also In general, if a name has already been defined, it is never overridden by another property of the same name.

So for above example, function a and the variable a has the same time, according to the name resolution order above, the function declaration will take precedence and it will not be overridden by the variable definition.That's why we have the above example to print out the function body instead of undefined.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


Windows 10 Deadlock

By sonic0002