Some of the most awesome JavaScript-side questions

Source: Internet
Author: User

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, what 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 "Advanced Programming of JavaScript"

(But the explanation for topic 2 seems a bit problematic)

OK, let's read the first question first.

Topic 1

If (! ( "A" in window)) {

var a = 1;

}

alert (a);

The code seems to say: If window does not contain property A, declare a variable a, and then 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 the statement var a = 1; equivalent to WINDOW.A = 1; You can detect if a global variable is declared as follows:

"Variable name" in window

Second, all the variable declarations are at the top of the range scope and look at similar examples:

Alert ("a" in window);

var A;

At this point, although the declaration is after alert, the alert pops 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:

var A;

Alert ("a" in window);

This 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:

var A; //Statement

A = 1; //Initialize assignment

When 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:

var A;

If (! ( "A" in window)) {

A = 1;

}

alert (a);

In this way, 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 the variable declaration

VO (global) = {

a: undefined

}

At this time a already had;

Then execute the code before you start walking the IF statement, for more information, see the 2 stages of the process context code in the in- depth understanding of the JavaScript series (12): Variable objects (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 2

var a = 1,

b = function a(x) {

X && A (--x);

};

alert (a);

This topic 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 advanced, and all function declarations are declared before the code is executed, and the variable

The same as the volume Declaration. To clarify, the function declaration is code such as the following:

function functionname(arg1, arg2){

//function Body

}

This is not a function, but a function expression, which is equivalent to a variable assignment:

var functionname = function(arg1, arg2){

//function Body

};

To 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:

function value(){

return 1;

}

var value;

Alert (typeof value); //"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:

function value(){

return 1;

}

var Value = 1;

Alert (typeof value); //"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 overwritten by the initialization of the variable, that is, if a (--x) is called an error, and other browsers are allowed to call a (--x) inside the function, because at this time a is still a number outside the function. Basically, IE makes a mistake when it 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:

var a = 1,

b = function(x) {

X && B (--x);

};

alert (a);

In this way, it is clear to know why alert is always 1, please refer to the "in-depth understanding of the JavaScript series (2): Secret named function expression" in the content.

Uncle Note: The installation of the ECMAScript specification, the author of the function declaration override variable declaration interpretation is actually inaccurate, the correct understanding should be as follows:

Go to the execution context: Here comes the name of the case, one is the function declaration, and the other is the variable declaration. Well, according to the in- depth understanding of the JavaScript series (12): Variable objects (Variable object) , the order of the filled VO is: the function declaration---------declaration of function.

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 3

function a(x) {

return x * 2;

}

var A;

alert (a);

This is the title of the title 2 of 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: Reference to function declaration "a"

}

When you execute a, the contents of function A are popped up accordingly.

Topic 4

function b(x, Y, a) {

arguments[2] = ten;

alert (a);

}

B (1, 2, 3);

On this topic, NC moved out of the 262-3 specification to explain, in fact, from the "in- depth understanding of the JavaScript series (12): Variable objects (Variable object)in the function context of the Variable object section can be clearly known, The active object is created at the moment of entry into the function context, and it 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, and it includes the following properties:

    1. Callee-a reference to the current function
    2. length-true number of arguments passed
    3. The value of the Properties-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 is equal to arguments.length. The value of properties-indexes is shared with the actual passed in parameters.

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] to assign values, it will be inconsistent, for example:

function b(x, Y, a) {

ARGUMENTS[2] = 10;

alert (a);

}

b(1, 2);

At this time because the third parameter A is not passed, so after assigning 10, alert (a) is still undefined, not 10, but the following code pops up the result is still 10, because it is not related to a.

function b(x, Y, a) {

arguments[2] = ten;

Alert (arguments[2]);

}

B (1, 2);

Topic 5

function a() {

Alert (this);

}

A.call (null);

This 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:

var Object = {

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:

function method() {

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:

function method() {

Alert (this = = = window);

}

Method (); //true

Method.call (document); //false

The 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:

function a() {

Alert (this);

}

A.call (window);

So the result of the popup is [object Window] is easy to understand.

Summarize

Although these 5 topics seem 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.

    1. Find the largest element in a numeric array (using the Match.max function)
    2. Converts a numeric array into a function array (each function pops up the corresponding number)
    3. Sort an object array (sorting criteria is the number of attributes per element object)
    4. Use JavaScript to print out the number of Fibonacci (without using global variables)
    5. The following syntax functions are implemented: var a = (5). Plus (3). Minus (6); 2
    6. The following syntax functions are implemented: var a = Add (2) (3) (4); 9

Some of the most awesome JavaScript face questions

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.