In-depth understanding of the JavaScript series (20): Do you really understand JavaScript? "Answer

Source: Internet
Author: User

introduce yesterday's "Uncle's Notes" (19): Do you really understand JavaScript? "Inside of the 5 topics, there are many answers, found that the strongman or a lot of people are all correct." Today, we will analyze these 5 topics in detail and hope to help you. Note: The problem comes from the famous front-end architect Baranovskiy's post "So, think you know JavaScript?". The answer is also from the famous JS bull Nicholas C. Zakas's post "answering Baranovskiy's JavaScript quiz"-the original author of the book "JavaScript Advanced Programming" ( But the explanation of topic 2 seems a bit problematic) OK, let's start with the first question 1if(! ("a"inchwindow)) {    varA = 1;} alert (a); The code appears to say: If window does not contain property A, declare a variable A and assign a value of 1. You might think that alert comes out with a result of 1, and then the actual result is "undefined". To understand why, we need to know 3 concepts in JavaScript. First, all global variables are properties of the window, and statementsvarA = 1; equivalent to WINDOW.A = 1you can detect if a global variable is declared as follows:"Variable name"inchwindow Second, all the variable declarations are at the top of the range scope and look at similar examples: alert (Ainchwindow);varA; At this point, although the declaration is after alert, the alert pop-up is still true because the JavaScript engine first graves all the variable declarations and then moves the variable declarations to the top, and the final code effect is this:varA;alert (Ainchwindow), which makes it easy to explain why the alert result is true. Third, you need to understand that the meaning of the topic is that the variable declaration is advanced, but the variable assignment is not, because this line of code includes the variable declaration and variable assignment. You can split the statement into the following code:varA//StatementA = 1;//Initialize Assignmentwhen a variable is declared and assigned together, the JavaScript engine automatically divides it into two parts in order to advance the variable declaration, not to advance the assignment because he has the potential to influence the code to perform unexpected results. So, after knowing these concepts, looking back at the code of the topic is actually equivalent to:varA;if(! ("a"inchwindow)) {a= 1;} alert (a); Thus, the meaning of the topic is very clear: first declare a, then determine whether a is in existence, if it does not exist on the assignment is 1, it is obvious that a always exists in the window, the assignment statement will never execute, so the result is undefined. Uncle Note: In advance this word seems a bit confusing, in fact, is the execution context of the relationship, because the execution context is divided into 2 stages: into the execution context and execution code, when entering the execution context, the creation of variable object VO already has: all parameters of the function, all function declarations, all variable declaration vo ( Global)={a:undefined} This time a already has, then executes the code only then starts to walk the IF statement, the detailed information please see "The Deep Understanding JavaScript series (12): The 2-step section of the processing context code in the Variable object (Variable object). Uncle Note: Believe that a lot of people think a in the inside is not accessible, the result is undefined it, in fact, there is already, but the initial value is undefined, not inaccessible. Topic 2varA = 1, b=functionA (x) {x&& A (--x); };alert (a); the subject looks more complicated than it really is, and the result of alert is 1; there are still 3 important concepts that we need to know. First of all, in topic 1 we know that the variable declaration is completed in the execution context, and the second concept is that the function declaration is also in advance, and all function declarations have been declared before executing the code, as are the variable declarations. To clarify, the function declaration is code such as the following:functionfunctionname (arg1, arg2) {//function BodyThis is not a function, but a function expression, which is equivalent to a variable assignment:varfunctionname =function(Arg1, arg2) {//function Bodyto clarify, the function expression does not advance, it is equivalent to the usual variable assignment. The third need to know is that the function declaration overrides the variable declaration, but does not overwrite the variable assignment, in order to explain this, let's look at an example:functionvalue () {return1;}varValue;alert (typeofValue);//"function"as soon as the variable declaration is defined below, but the variable value is still function, that is, the function declaration takes precedence over the variable declaration priority, but if the variable value is assigned, the result is completely different:functionvalue () {return1;}varValue = 1; alert (typeofValue);//"Number"after the value is assigned, the variable assignment is initialized to overwrite the function declaration. Back to the topic, this function is actually a well-known function expression, the function expression is not like a function declaration can overwrite the variable declaration, but you can notice that the variable B contains the function expression, and the function expression name is a; A is considered a function declaration, so it is overridden by the initialization of a variable, that is, if a is called a (--x), and other browsers are allowed to call a (--x) inside the function, since a is still a number outside the function. Basically, IE calls B (2), but other browsers return undefined. After understanding the above, the topic should be replaced by a more accurate and understandable code like this:varA = 1, b=function(x) {x&& B (--x); };alert (a); In this way, it is clear why alert is always 1, please refer to the in-depth understanding of the JavaScript series (2): Reveal the contents of the named function expression. Uncle Note: The installation of the ECMAScript specification, the author of the function declaration overrides the interpretation of the variable declaration is not accurate, the correct understanding should be as follows: into the execution context: here is the name of the case, one is a function declaration, one is a variable declaration. Well, based on an in-depth understanding of the JavaScript series (12): Variable objects (Variable object), the order of the filled Vo is: function declaration---variable declaration. In the example above, variable A is behind function A, so what happens to variable a when it encounters function a? Or, as described in the variable object, when the variable declaration encounters the same name already exists in Vo, it does not affect the existing property. The function expression does not affect the content of VO, so B triggers the contents only when it executes. Topic 3functionA (x) {returnX * 2;}varA;alert (a); This is the title 2 in the Uncle Plus comments, that is, function declaration and variable declaration of the relationship and influence, encountered the same name function declaration, VO will not be redefined, so this time the global VO should be as follows: VO (global)={A: Referencing the function declaration "a"} and executing a, the contents of function A are ejected accordingly. Topic 4functionb (x, Y, a) {arguments[2] = 10; alert (a);} B (1, 2, 3) on this topic, NC moved out of the 262-3 specifications come out to explain, in fact, from the "deep understanding of the JavaScript series (12): A Variable object in the context of a function in a variable object (Variable object) can be clearly known that the active object is created at the moment of entry into the function context and is initialized by the arguments property of the function. The value of the arguments property is the arguments object: AO={arguments:<ArgO>}; The arguments object is a property of the active object that includes the following properties: callee-a reference to the current function length-the number of parameters actually passedThe value of the-indexes (integer of String type) property is the parameter value of the function, arranged from left to right in the argument list. Properties-indexes the number of internal elements equals arguments.length. properties-The value of the indexes is shared with the arguments actually passed in. This share actually does not really share a memory address, but 2 different memory addresses, using the JavaScript engine to ensure that 2 values are always the same, of course, there is a premise, that is, the index value is less than the number of parameters you passed in, that is, if you only pass in 2 parameters, and continue to use arguments[2], the assignment will be inconsistent, for example:functionb (x, Y, a) {arguments[2] = 10; alert (a);} B (1, 2At this point, because the third parameter A is not passed, the result of alert (a) is still undefined, not 10 after the assignment of 10, but the following code pops up with 10 because it is not related to a. functionb (x, Y, a) {arguments[2] = 10; Alert (arguments[2]);} B (1, 2); topic 5functionA () {alert ( This);} A.call (NULLThis topic can be said to be the simplest, but also the most bizarre, because if you do not learn its definition, kill will not know the result, on this topic, we first to understand the 2 concepts. First, it is how the this value is defined, and when a method is called on the object, this points to the object, for example:varObject ={method:function() {alert ( This= = = object);//true}}object.method (); The code above, called method (), is pointed to the object that called it, but in the global scope, this is equivalent to window (in the browser, not the browser equivalent to global), If the definition of a function is not a property of an object (that is, a function that is defined separately), the internal this is also equivalent to window, for example:functionmethod () {Alert ( This= = = window);//true}method (); Having learned the above concepts, let's look at what call () does, and the call method acts as a function delegate that allows another object to be invoked as a caller, and the first argument to the calling method is the object caller. The other arguments that follow are passed to the parameter that calls method (if declared), for example:functionmethod () {Alert ( This===window);}    Method (); //trueMethod.call (document);//falseThe first one is still true. There is nothing to say, the second incoming call object is document, which naturally does not equal window, so it pops up false. In addition, according to the ECMAScript262 specification, the call method takes the global object (that is, window) as the value of this if the object caller passed in by the first parameter is null or undefined. So, no matter when you pass in NULL, its this is the Global object window, so the topic can be interpreted as the following code:functionA () {alert ( This);} A.call (window), so the result of the popup is [object window] is easy to understand. The summary of these 5 topics, although seemingly a bit biased, but in fact the survey is still the basic concept, only the knowledge of these basic concepts to write high-quality code. The basic core content and understanding of JavaScript is basically the end of the series, the next chapters in addition to the five principles of the remaining 2 complete, will add two articles about the DOM, Then we began to turn to the article about JavaScript patterns related to design patterns (about 10 articles), then spend a few chapters on a practical series. More topics If you are interested, you can continue to study the following topics, detailed through these topics can also deepen the understanding of the core features of the JavaScript base. Uncle Note: These topics are also from these 5 subjects, of course, if you can correct 4 and above and want to get high wages, please contact me. Find the largest element in the array of numbers (using the Match.max function) to convert a numeric array into a function array (each function pops up the corresponding number) to sort the object array (the number of attributes for each element object is sorted) to print out Fibonacci with JavaScript Number (do not use global variables) to implement the following syntax functions:varA = (5). Plus (3). Minus (6);//2Functions that implement the following syntax:varA = Add (2) (3) (4);//9synchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

In-depth understanding of the JavaScript series (20): Do you really understand JavaScript? "Answer

Related Article

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.