Write the output of the following question

1、 The real and formal parameters of a function length

var length = 10;
function fn() {
console.log(this.length);
}
var obj = {
length: 5,
method: function(fn) {
fn();
arguments[0]();
}
};
console.log(obj.method(fn, 1)); // 0 2

We all know ,[1, 2, 3].length You can get 3,"123".length You can get 3, that Functional length What do you get ?

function test(a,b,c) {}
test.length // 3
function test(a,b,c,d) {}
test.length //

You can see , Functional length Seems to have returned the number of arguments , Is there any difference between formal parameters and actual parameters ? The answer is yes. .

function test() { console.log( arguments.length );}
test(1,2,3); // Output 3
test(1,2,3,4); // Output 4

You can see , In the function , use arguments.length What we get is the number of actual parameters of the function .

in addition , We need to know var length = 10 It's impossible to write like this , because length yes JavaScript Built-in properties , Cannot be used as variable or function name . Poke it here http://www.runoob.com/js/js-reserved.html see JavaScript What are the reserved keywords 、 Built in properties, etc .

therefore , When executed fn() when ,this.length Print is fn The number of formal parameters of this function , by 0; And perform arguments[0]() when , It's actually obj.method() This method is arguments Called fn function ,this.length Of this Pointing to arguments, His actual number of parameters is 2.

2、 The process of parsing and preanalysis of functions ( Variable Promotion )

function fn(a) {
console.log(a); // function a() {alert(1)}
var a = 2;
function a() {alert(1)}
console.log(a); //
}
fn(1);

It's still a big problem .. I thought about it for a long time .. Let me talk about it , It involves the parsing and pre parsing of functions .

First meet function fn Such a function declaration , Meeting Perform function preanalysis This is a process , What is function preanalysis ? Generally speaking, it means , From the body of the function Look for variables and function declarations The process of , Variables found ( encounter var You find the variable ) Don't read specific values , It can only be endowed with undefined; The function declaration found is assigned to the entire function body , Here is a point of knowledge Namely , If you find a variable with the same name as the declaration , Then the declaration will override the variable ( My understanding is that , After all, the function volume ratio undefined It's very strong ).

In this case , Variables found during pre parsing a, And the assignment is undefined, Found the statement function a(){alert(1)}, For the whole function body ; They have the same name , So the declaration covers variables a Value ,a No more undefined Of , It's the body of the function .

The method is called after preparsing , Start step by step . First console.log(a), The function body is printed out ; next var a = 2,a The value of is changed from the body of the function to 2 ; And then there's a function a(){} Function declaration , Be careful , A declaration cannot change the value of a variable , So finish this sentence ,a The value of the or 2, And then it prints out 2.

Some people must have such doubts , Why? a=1 It didn't work ? Here's a principle , Namely Local variables take precedence , Based on this principle , Let's analyze it again a Change process of . In pre analysis ,a=undefined,a=function(){alert(1)}, In this case, the parameter has a value equal to 1, It should have been a The assignment is 1, But there is no , The reason is that at this time a Is already equal to the local function declaration function(){alert(1)}, So the parameters from the outside 1 It doesn't replace a Value ; If this example does not have function(){alert(1)} This sentence , It will print out 1,  2.

Local variable priority principle , The principle is the same as below :

var a = 5;
function fn(){
var a = 10;
console.log(a) // 10, Local variables take precedence , It's found locally a after , No more looking out
}

3、 Variable Promotion 、window The variable of

if('a' in window) {
var a = 10;
}
console.log(a); // 10

First ,if(){} It's not like function(){} It's like curly braces , Has its own block level scope ,if The curly braces are the global environment . according to JavaScript Variable promotion mechanism of ,var a Will be js The engine explains to the first line , as follows :

var a;
if ('a' in window) {
a = 10;
}

And then there's a knowledge point , The global variable is window Object properties , therefore 'a'  in  window Returns the true, The answer is straightforward .

I stepped in a hole when I was doing this problem , I wrote the following code in the code editor :

window.onload = function(){
if('a' in window){
var a = 10;
}
console.log(a) // undefined
}

Now ,a This variable is defined in the anonymous function function(){} Inside , Local variables belonging to the function , therefore a No more window The object of . We must pay attention to the details .

4、 The base type has no attributes

var a = 10;
a.pro = 10;
console.log(a.pro + a); // NaN
var s = 'hello';
s.pro = 'world';
console.log(s.pro + s) // undefinedhello

Variable a And s All basic types , Can't add properties to them , therefore a.pro and s.pro All are undefined.

undefined + 10 obtain NaN(not a number).

undefined + 'hello' obtain undefinedhello, among undefined Is converted to string type .

If you really want to add properties to a string , We need to define a string as a string of object type , as follows :

var a= new String('objectString')
a.pro = "aaaaaaa"
console.log(a.pro) // aaaaaaa

5、async And await Implementation

async function sayHello() {
console.log('Hello')
await sleep(1000)
console.log('world!')
}
function sleep(ms) {
return new Promise(resolve => {
console.log("666666");
setTimeout(resolve, ms);
console.log("888888")})
}
sayHello() // hello 666666 888888 world!

async That means this is one async function ,await It can only be used in this function .

await To wait here promise Returned the result , And go on with it .

First of all hello, here we are await, Will wait for promise Return , therefore “world” Not immediately , Then enter the sleep function , play 666, And then there was a 1 Second timer , although js It's single threaded , but setTimeout It's asynchronous , In the browser , Asynchronous operations are all added to a process called “events loop” The place in the queue , The browser will only execute the code in this way after all synchronization code is executed , therefore resolve Being added to the task queue , First print 888, A second later it was executed resolve, Express promise Successfully returns , Played the world.

Each of the above questions is my own idea and understanding , If there is any mistake, please correct it , Big guy light spray ~

Middle and advanced JavaScript More about fallible interview questions

  1. JavaScript Sorting out fallible knowledge points

    Preface This is my study JavaScript Some error prone knowledge points collected and sorted out in the process , From the variable scope , Type comparison ,this Point to , Function parameter , Closure problem and object copy and assignment 6 This paper introduces and explains from the simple to the deep in three aspects , It also involves a ...

  2. JavaScript Sorting out fallible knowledge points

    This is my study JavaScript Some error prone knowledge points collected and sorted out in the process , From the variable scope , Type comparison ,this Point to , Function parameter , Closure problem and object copy and assignment 6 This paper introduces and explains from the simple to the deep in three aspects , It also involves some ES ...

  3. JavaScript Error prone point reprint

    Preface This is my study JavaScript Some error prone knowledge points collected and sorted out in the process , From the variable scope , Type comparison ,this Point to , Function parameter , Closure problem and object copy and assignment 6 This paper introduces and explains from the simple to the deep in three aspects , It also involves a ...

  4. 《java Season one 》 Object oriented ( A fallible interview question )

    This interview question is a bit difficult , There are some . I don't understand. I can discuss it below . It's worth understanding . / * Look at the result of the program : A: The problem of member variable int x = 10; // Member variables x Is the basic type Student s = new St ...

  5. JavaScript Sorting out fallible knowledge points [ turn ]

    Preface This is my study JavaScript Some error prone knowledge points collected and sorted out in the process , From the variable scope , Type comparison ,this Point to , Function parameter , Closure problem and object copy and assignment 6 This paper introduces and explains from the simple to the deep in three aspects , It also involves a ...

  6. JavaScript It's easy to get wrong

    JavaScript Knowledge point 1. Variable scope   var a = 1;function test() {    var a = 2;     console.log(a); // 2} test();   ...

  7. 10 Avenue C++ Output error prone written test questions collection

    The following questions are all accumulated in the process of preparing for the written interview , Most of them are written questions from well-known companies ,C++ Those with weak foundation are easy to fall into . I chose 10 A simple question ,C++ Beginners can come in and challenge ,C++ Daniel can also play as entertainment ( Like the following ...

  8. JavaScript It's easy to get wrong -- Array comparison

    Remember the beginning of learning JavaScript Try it out “==” or “===” Compare two arrays for equality , var a = [1,2,3] var b = [1,2,3] if(a == b){ //false //do s ...

  9. javascript It's easy to get wrong 、 Difficult notes

    This paper mainly records the problems encountered in the process of learning JavaScript Difficult or easily overlooked details , It's also convenient for you to read and study in the future . 1.arr.length === + arr.length arr.length === + arr ...

Random recommendation

  1. Html Document flow and document object model DOM understand

    Preface In understanding floating and positioning , Touch the concept of document flow . To better understand floating and positioning , Learned about document flow and DOM( Document object model ). Text DOM( Document object model ) Simple understanding is written html The tree structure of all the contents of the page . for example : root ...

  2. To relive WCF Data contract and serialization ( Four )

    One . Data contract 1. Using data contracts can flexibly control which members should be recognized by clients . [DataContract] public class Employee { [DataMember] public string ...

  3. Scrollview nesting RecyclerView And in Android 5.1 Version sliding The problem of inertia disappearing

    label :scrollview   android    slide     nesting scrollview nesting recyclerview when ,recyclerview No display , This requires us to calculate recyclerview ...

  4. Android ListView Simple use of list control

    ListView Lists are controls that we often use , If you want to customize the display inside, it's very troublesome , Need new XML.Class SimpleAdapter These two documents , More troublesome . If we just want to show two . Three lines ...

  5. Ubuntu Next nginx+uwsgi+flask Build the execution environment of

    choice web framwork It's a very difficult thing , It is mainly divided into lightweight and heavyweight framework . Because there is no need to build a site like this , So avoid SSH, Django Such a framework , And choose a lightweight framework . I also prefer pyth ...

  6. C# DES Symmetric encryption and decryption

    /// <summary> /// encryption /// </summary> /// <param name="str"></param> ...

  7. 【BZOJ1007】 A straight line can be seen horizontally ( Monotonic stack )

    [BZOJ1007] A straight line can be seen horizontally ( Monotonic stack ) Answer key Description stay xoy There's... In the Cartesian plane n A straight line L1,L2,...Ln, If in y If the value is positive infinity, look down , You can see it Li Some sub line segment of , said Li by Visible ...

  8. springboot12-zuul

    Zuul It's equivalent to equipment and Netflix The application of flow Web The back end of the site is the front door for all requests , Provide dynamic routing , monitor , elastic , Edge services for security, etc All requests go through the gateway (API Gateway)zuul, And then forward to the sub Services ...

  9. Chat Python Medium is and ==

    First ,Python Medium is Is to determine whether the addresses are equal ( amount to Java Medium ==),Python Medium == Is to determine whether the values are equal ( amount to Java Medium equals). Take a simple example : a = [1, 2, 3] b ...

  10. iOS Learn as you practice --plist file , Lazy loading , The model was first used -- Add instancetype

    One . What is? plist file 1> Write the data directly into the code , It's not a reasonable thing to do . If the data is constantly modified , It is necessary to frequently open the corresponding code for modification , Cause low code scalability 2> therefore , You can consider putting frequently changed data in a file ...