"Translation" Zakas solution to Baranovskiy's JavaScript puzzle

Source: Internet
Author: User

Original: http://www.nczonline.net/blog/2010/01/26/answering-baranovskiys-javascript-quiz/

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------

Last week I read a few questions about JavaScript in a Dmitry Baranovskiy blog titled, "Do you think you really know javascript?" Like this type of topic, you just have to answer a question: what is the result? These examples are used to test some of the bizarre behavioral behavior of JavaScript engines. I've seen this type of quiz before, and some people use it as an interview, and I think it's not only disrespectful to the interviewer, it's useless. You will not encounter this type of weird problem every day, so using this kind of question to examine the interviewer, as the lowest indicator, is as useless as asking someone to explain the principle of airplane flight when interviewing a stewardess.

But I still like these examples, they can be very good to explain the JavaScript language interesting phenomenon, below I will be in-depth analysis of how each quiz question is executed.

Quiz 1

1 if inch window)) {2     var a=1; 3 }4 alert (a);

This seemingly strange piece of code seems to say: "If the Window object does not have property ' a ', then define a given to it and set its value to 1". You might think that the result of the pop-up is 1, in fact the result is ' undefined ', and to understand why, you need to know three things about JavaScript.

First, all global variables are a property of the Window object, and you write ' var a=1; ' Equivalent to writing ' window.a=1; ', you can use the following method to detect whether a global variable is declared:

1  in Window

Second, all variable declarations advance to the top of the current scope, see the following code:

1 inch window); 2 var A;

The above result is ' true ', although the variable declaration statement is after the detection statement, but because the JavaScript engine first scans the variable declaration and then moves them to the top of the current scope, the final parsed code is as follows:

1 var A; 2  in window);

Looking at this code makes it easier to understand why the result is ' true '.

Third, you need to know that although the variable declaration is advanced, the assignment does not. The following statements are variable declarations and assigned values:

1 var a=1;

You can divide it into two parts: Declaration and assignment.

1 var A; // Statement 2 // Assign Value

When the JavaScript engine discovers that the declaration and assignment are together, it will automatically separate them and then advance the declaration. Why is the assignment not advanced? This affects the value of the variable and produces unexpected results when the code executes.

Now that you understand these features of JavaScript, look again at the code for Case 1, which is actually parsed into the following code:

1 var A; 2 if inch window)) {3     a=1; 4 }5 alert (a);

After looking at the code, the answer is obvious. First declare the variable ' a ', followed by the IF statement, and say, "If ' a ' is not declared, then it is initialized to 1". Of course, the conditional judgment cannot be ' true ', so the value of the variable is still the default value ' undefined '.

Quiz 2

1 var a=1,2     b=function  A (x) {3         x&&a (--x) ; 4     }; 5 alert (a);


This code is more complex than it looks, and the result is ' 1 ', which is the initialized value. But why is that? This still requires an understanding of the three main points of JavaScript.

The 1th is the declaration in advance, in case 1 has been told.

2nd, the function declaration is advanced. All function declarations, like variable declarations, are advanced to the top of the current scope, but understand that the function declaration is:

1 function functionname (arg1,arg2) {2     // function Body 3 }

The following is not a function declaration, but a function expression, which is equivalent to a variable assignment:

1 var functionname=function(arg1,arg2) {2     ///  function Body3 }

To be clear, the function expression is not advanced. It is now important to understand that, because the initialization of variables and the change of assignment position will significantly affect the execution of the program.

3rd, the function declaration takes precedence over the variable declaration, but does not overwrite the assignment of the variable. To understand the meaning of this sentence, take a look at the following code:

1 function value () {2     return 1; 3 }4var  value; 5 alert (typeof//' function ' )

Even though a variable is declared after a function declaration, the value of the variable ' value ' is still a ' function ', in which case the function declaration has a higher precedence. However, if the variables are initialized, the results will be different.

1 function value () {2     return 1; 3 }4var value=1; 5 alert (typeof// number

Now that the value of the variable is set to 1, the initialization of the variable overrides the function declaration.

Back to the code in quiz 2, the function is a name-function expression. A function expression with a name is not a function declaration, so the variable declaration is not overwritten. However, you should note that the value of variable B is a function expression, and the function name of the function expression is a, and different browser processing methods are different. IE will treat it as a function declaration, so it will be overwritten by the initialization of the variable, then calling a (--x) will cause an error. As for other browsers, although a is a number outside the function, a (--x) can still be called within the function. Basically, invoking B (2) in IE throws a JavaScript exception, but in other browsers it returns ' undefined '.

After understanding the above, replace the topic with a more accurate and understandable version:

1 var a=1,2     b=function(x) {3         x&&b (--x); 4     }; 5 alert (a);

In this case, it is clear that the value of variable A is always 1.

Quiz 3

1 function A (x) {2     return x*2; 3 }4var  A; 5 alert (a);

If you understand the example above, then the problem is very simple. One thing to keep in mind is that a function declaration always takes precedence over a variable declaration, which means that the variable declaration statement is ignored, unless the variable initialization is encountered. There is no initialization, so the popup result is the source code of function A.

Variables with the same name are not declared repeatedly.

Quiz 4

function B (x,y,a) {    arguments[2]=10;    alert (a);} B (a);

This code is better understood, as long as the result is ' 3 ' or ' 10 ', all the browser results are 10. As long as you know a concept, you know why the result is, that is, the ECMA-262 third edition of the 10.1.8 section about arguments objects:

1For each non-negative integer, arg, less than the value of the length property, a property is created withName ToString (ARG) and property attributes {Dontenum}. The initial value of ThisProperty was the value of the corresponding actual parameter supplied by the caller. The first actual parameter value corresponds to ARG = 0, the second to arg = 1, and so on. In the CaseWhen Arg was less than the number of formal parameters forThe Function object, ThisProperty shares its value withThe corresponding property of the activation object. This means, that changing ThisProperty changes the corresponding property of the activation object and vice versa.2Too TM hard to understand: For each nonnegative integer, the number of arguments passed in is smaller than the ' length ' property value, then ToString (ARG) is used to create a property and attribute variable ' {dontenum} '. The initial value of this property is the number of arguments passed in by the caller. The first argument corresponds to Arg=0, the second corresponds to a arg=1, and so on. When the number of arguments is less than the formal parameter, this property shares the value with the active object. This means that changing the value of a property changes the properties of the corresponding activated object, and vice versa.

In short, each entity in the arguments object is a copy of the formal parameter, although the value is shared, but the memory space is not shared. Two memory spaces are saved by the JavaScript engine, which means that arguments[2] and a always have the same value, so the final value of a is 10.
Quiz 5

1 function A () {2     alert (this); 3 }4 a.call (null);

I think this is the simplest of the 5 questions, just to understand the two concepts.

First, you need to know how the value of this is defined, and when a method is called by an object, this points to the object, for example:

1 var object={}2     method:function  () {3         alert (this  //true4    }5; 6 Object.Method ();

In this code, when Object.Method () is called, this points to object. In the global scope, this is equivalent to window (that is, the global object), so if a function definition is not part of an object property (that is, a function that is defined separately), the inside of the functions is equal to the window, for example:

1 function method () {2     alert (this//true3}4 Method ();

Here, this refers to the Global object window.

Having learned the concepts above, let's take a look at what the call () method does. The call method allows a method to be called as a method of another object, the first parameter is the caller, and the other parameter is the argument to the method being called, for example:

1 function method () {2     alert (this = =window); 3 }4//true5//false

This is called by the document because of method (), so the result is ' false '.
An interesting question is what happens when one of the parameters of the incoming call method is NULL, the following is a description of the issue in ECMA-262 Third Edition:

1 If the first parameter passed in is ' null ' or ' undefined ', then the call method takes the Global Object (window) as the value of this, otherwise the value of this is equal to Toobject (Thisarg).

So whenever the call () and the Apply () method pass in null for the first argument, the value of this is window. Based on the above knowledge, the case 5 code is changed to the following easier to understand:

1 function A () {2     alert (this); 3 }4 a.call (window);

The obvious result is [object Window].

Summarize

Dmitry put these interesting quizzes together, you can learn some of the weird features of JavaScript, and I hope this article will help everyone understand the details of how these examples run, and more importantly, understand why. To reiterate, I object to the ability to test the interviewer with this type of quiz as a face test, which I think is of little use in practice (if you want to know how I interviewed front-end engineers, see my previous article).

"Translation" Zakas solution to Baranovskiy's JavaScript puzzle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.