This is a summary of some of my notes in the study, including closure, scope, prototype and so on. These will be presented to you in the way of interview questions, the full text is divided into JS Basic, JS advanced, jQuery and VUE four parts, read carefully and type code several times, you will benefit a lot, and HOPE you criticize and correct.

1. The closure

What is a closure?

The definition of A closure is simple: function A has A function B inside it, and function B can access variables in function A, so function B is A closure.

function A() {let a=1;                 
    window.B=function(){ console.log(a) } } A(); B(); / / 1Copy the code

Many people interpret closures as functions that nest functions and then return a function. In fact, this explanation is incomplete, as my above example can refute this view.

In JS, closures exist to give you indirect access to variables inside a function.

Use closures to solve the problem of ‘var’ defining functions in a loop.

Requirements: Output a number every second, from 0 to 5;


for(var i=0; i<=5; i++){setTimeout(function timer(){                
        console.log(i)            
    },i*1000)        
}        
console.log(i)Copy the code

Output results: output a 6 immediately, and then output a 6 every second;

First of all, since setTimeout is an asynchronous function, it will execute the entire loop first, and then I will be 6, so it will print a bunch of 6’s.

There are three solutions.

The first is to take advantage of closures:

for(var i=0; i<=5; i++){ (function(j){                
        setTimeout(function timer(){                    
            console.log(j)                
        },j*1000)            
    })(i)        
}Copy the code

In the above code, we first use the immediate execution function to pass I into the function. At this time, the value is fixed on the parameter j and will not change. The next time the timer closure is executed, we can use the variable j of the external function to achieve this goal.

The second is to use the third argument of setTimeout, which is passed in as an argument to the timer function.

for(var i=0; i<=5; i++){setTimeout((j) => {                
        console.log(j);            
    },i*1000,i)        
}Copy the code

SetTimeout also allows more arguments. They, in turn, pass in deferred functions (callbacks).

setTimeout((a,b,c) => {            
    console.log(a,b,c)        
}, 2000, "my"."name"."is starsion");
//my name is starsionCopy the code

For more information on the use of setTimeOut, please refer to Mr. Ruan YifengTimer for asynchronous operations

The third way is to use let definition I to solve the problem, and this is the most recommended way

for(leti=0; i<=5; i++){setTimeout(() => {                    
        console.log(i)                
    },i*1000)            
}Copy the code

For more information on the difference between let and var, please refer to teacher Ruan Yifeng’s let command

2. JS scope

Prior to ES6, JS had no block-level scope. For example,

if (true) {
    var name = 'zhangsan'
}
console.log(name)Copy the code

The above example illustrates the concept of a scope. A scope is an independent domain that keeps variables from leaking out. The name above is exposed, so JS has no block-level scope, only global and function scope.

However, ES6 started to add block-level scoping, so you can define variables using let

if (true) {
 let name1 = 'zhangsan'} console.log(name1letThe name defined is inifThis is block-level scopeCopy the code

1. Js scopes (global scope and function scope) can access the external, but the external cannot access the internal

var a=10;        
function aaa(){ alert(a); }; aaa(); / / 10Copy the code

function aaa(){            
    var a=10;          
};        
aaa();        
console.log(a)//Uncaught ReferenceError: a is not definedCopy the code

var a=10;         
function aaa(){ console.log(a); / / 10};function bbb(){ var a=20; aaa(); } bbb(); / / 10Copy the code

function aaa(){            
    a=10;         
}        
aaa();        
function aaa(){            
    var a=b=10;         
}      
aaa();      
console.log(b)//10    
console.log(a)//Uncaught ReferenceError: a is not definedCopy the code

2. If you do not use var to define a variable, it will default to global (not standard, not recommended)

function aaa(){            
    a=10;         
}        
aaa();        
function aaa(){            
    var a=b=10;         
}        
aaa();        
console.log(b)        
console.log(a)Copy the code

3. The search of variables is to look for the defined var variable according to the nearest principle;

Variable declarations are advanced to the top of the scope, and assignments are left where they are, as in domo;

function aaa(){ console.log(a); //undefined var a=20; } aaa();Copy the code

var a=10;        
function aaa(){ console.log(a); //undefined var a=20; } aaa();Copy the code

var a=10;        
functionaaa(a){ console.log(a); //10 var a=20; Var a; var a; var a; So the declaration of the local variable A is actually ignored. } aaa(a);Copy the code

3. Scope chain

So let’s first understand what a free variable is. In the following code, console.log(a) gets the variable a, but a is not defined in the current field (compare b). Variables that are not defined in the current scope become free variables. Where to get the free variable — look for the parent scope.

var a = 100;
function fn() {
    var b = 200;
    console.log(a);
    console.log(b);
};
fn();Copy the code

What if the parent doesn’t? Another layer of upward search, until found the global scope or not found, announced to give up. This layer-by-layer relationship is called the scope chain.

var a = 100;
function F1() {
    var b = 200;
    function F2() { var c = 300; Console. The log (a) / / free variables, suitable scope chain to the parent scope for the console, log (b) / / free variables, suitable scope chain to the parent scope for the console. The log (c) / / the scope of the variable}; F2(); }; F1();Copy the code

Scope additional questions:

1. Determine the output and explain why?

var a = 1;        
(function a() { a = 2; console.log(a); }) (); // Output result ƒa () {
           a = 2;
           console.log(a);
       }Copy the code

Now, when you look at this, a lot of people think console.log of a is 2, but it’s not,

Instant-call function expressions (IIFE) have their own independent scope, and if a function name conflicts with an internal variable name, the function itself is executed forever; So the output above is the function itself;

If you change the name of the function, say, to x

var a = 1;        
(function x() { a = 2; console.log(a); }) (); / / 2Copy the code

The name of a function in a function expression is available only in its own scope and does not affect the whole function

var a = 1;        
(function a() { a = 2; console.log(window.a); }) (); / / 1Copy the code
var a = 1;        
(function x() { a = 2; console.log(a); }) (); / / 2Copy the code

JS basic interview questions

1. Introduce arguments in JS.

【考 题 : function of arguments】

The special object Arguments is used in the function code to allow developers to access arguments without specifying their names.

For example, in the function sayHi(), the first argument is message. This value is also accessed using arguments[0], which is the value of the first argument (the first argument is at position 0, the second argument is at position 1, and so on).

Therefore, the function can be overridden without explicitly naming the arguments:

function sayHi() {  
    if (arguments[0] == "bye") {    
        return;  
    }  
    alert(arguments[0]);
}Copy the code

Click to see about the Arguments object

Num = (D) num = (D)

【考 题 】

var num;              
num=5+true; A,trueB,falseC, 5 D, 6Copy the code

True = 1; false = 0; The following code

console.log(true/ / = = 1)true
console.log(true/ / = = = 1)false
console.log(false/ / = = 0)true
console.log(false/ / = = = 0)falseCopy the code

【考点 : switch statement,break】

var   x=prompt("Please enter the number 1-5."."");                     
switch (x) {                            
    case"1" : alert (" one ");case"2" : alert (" two ");case"3" : alert (" three ");case"4" : alert (" four ");case"5" : alert (" five "); Default: alert (" none "); }Copy the code

Run the above program, enter “4” in the prompt dialog box, and the dialog box will output: (B)

A, four,none B, four,five,none C,five D,five,noneCopy the code

Parsing: because after the execution, there is no break, the code will continue to execute.

4. Analyze the following JavaScript snippet

(B) The answer is (C) the answer is (D) the answer is (D) the answer is (D) the answer is (D) the answer is (D) the answer is (D)

A = new Array (2,3,4,5,6); sum=0;for(i=1; i<a.length; i++ ) sum +=a[i]; document.write(sum); A. 20 B. 18 C. 14 D. 12Copy the code

Note: I starts at 1, don’t fall into the pit.

5. In HTML, the () property of the Location object is used to set or retrieve the port number for the URL. (B)

【考 试 题 : Location object 】

A.  hostname   B.  Port    C. pathname  D.  hrefCopy the code

The Location object provides the following properties.

  • Location.href: The entire URL.
  • Location.protocol: Protocol of the current URL, including colons (:).
  • Location.host: host, including colon (:) and ports (the default ports 80 and 443 are omitted).
  • Location.hostname: Indicates the host name, excluding the port.
  • Location.port: Indicates the port number.
  • Location.pathname: The path portion of the URL, from the root path/Start.
  • Location.search: Query part of the string from the question mark?Start.
  • Location.hash: Fragment Part of a string, from#Start.
  • Location.username: Indicates the user name before the domain name.
  • Location.password: The password before the domain name.
  • Location.origin: Protocol, host name, and port of the URL.

For more information about the Location object, click here.

6. Analyze the following javascript code:

x=11;
y="number"; m= x+y ; (A) a. 11b b. 11C C. 11D. Application errorCopy the code

7, setInterval (” alert (‘ welcome ‘);” , 1000); 【考 题 】

(D) A. Wait 1000 seconds, then A dialog box will pop up B. A dialog box is displayed after 1 second. C. A dialog box pops up every secondCopy the code

8, analyze the following JavaScript code:

Var a = 15.49; document.write(Math.round(a)); The output is (A) A.15B.16C.15.5d.15.4Copy the code

Math.ceil() rounding up

Math.floor() rounds down

Math.round() Performs standard rounding

To learn more about Math objects, click on Math Objects

Ruan yifeng standard library Math object

9. Analyze the following JavaScript snippet where b has the value (C)

【考 题 】

Var a = 1.5, b; b=parseInt(a); A. 1 B. 2 C. 1 D. 2Copy the code

Parsing: The parseInt() function converts a string to an integer. It starts parsing at the beginning of the string, stops parsing at the first non-integer bit, and returns all the previously read integers, or NaN(Not a Number) if the string does Not start with an integer.

Click to viewThe parseInt () usage

10. In form1, there is a text box element (fname) for entering a phone number. The format is 010-82668155, and the first three digits must be 010 followed by a hyphen (-) followed by eight digits. Requires that the input in the text box be validated against the above criteria when submitting the form,

Substr () is used to intercept a string to determine if it is a number.

var str= form1.fname.value;        
if(STR. Substr (0, 4)! ="010 -"||str.substr(4).length! =8 || isNaN(parseFloat(str.substr(4)))) alert("Invalid phone number!");Copy the code

Resolution:

Substr (m, n) to intercept a character at a time, two parameters m, n, said from m bit (not including m), to intercept back n; If I write only one argument m, I’ll take everything after that argument;

IsNaN determines if the character isNaN (not a number) and returns true if it is not all digits; Returns false if it is all numeric.

11. Which of the following words is not a reserved word in javascript?

Use reserved words in javascript to prevent naming errors.

A.with      B.parent     C.class     D.voidCopy the code

Key words 26 Breakcase catchcontinue  debugger  default  delete  doelsefinally  for  function  
if  in  instance  new  returnSwitch this throw try typeofvar voidwhile with reserved string abstract Boolean ByTEChar class const double enumexport   extends  final floatgoto implements import int interface long native package private protected public short static super synchronized throws  transient volatileCopy the code

Using a keyword as an Identifier in a JavaScript engine results in an “Identifier Expected” error

12. Please select the expression with true result :(C)

【 近 】 null, undefined, NaN

A.null instanceof Object //false
B.null === undefined  //false
C.null == undefined //true
D.NaN == NaN //falseCopy the code

[C]NaN operation rules  Null, and undefined

13. Which of the following operators is not a logical operator? (C)

Logical operators and bitwise operators

1. A and B &&, | |, ^ D, C!Copy the code

The Boolean operator is used to convert an expression to a Boolean value. The first three are called logical operators

  • Take the inverse operator:!
  • And the operator:&&
  • Or operator:||
  • Ternary operators:? :

Click to see moreKnowledge of operators

14, the following define variable error is (D).

【考 题 】

A, eee B, _abc C, box_1 D, 2pointCopy the code

Resolution:

  • Variables are composed of letters, numbers, underscores, or the dollar sign $.
  • The first character can be a letter, an underscore, or the dollar sign $;
  • Subsequent characters can be letters, numbers, underscores, or dollar signs;

  • Variable names are case sensitive

  • Reserved words, keywords, JavaScript predefines many global variables and functions that cannot be used as custom variable and function names

  • Convention commonly known: identifier to see the name to know the meaning;

Hump nomenclature: Also known as lesser hump nomenclature. It is usually used to name variables, to explain and describe variables

For example: var planeBulletSpeed; // The speed of an airplane bullet

Var x= -10, y; x=2*x; y=x+15; The result of y is (C).

【考 题 】

A, B, C, D, 5Copy the code

16, the following expression evaluates to true (B D).

【考 题 】 Click to view the logical operator

A, 1 < 2 &&"5"! = 5 / /falseB, 2 > 2 * 1 | |"5"= = 5 / /trueC, 2>2*1 && 5 ==5 //falseD, 1 < 2 &&"5"= = 5 / /trueCopy the code

17, the following section, the result of execution is (C).

A while loop is used to avoid an infinite loop unless it is necessary.

var x=-1; 
do{   
    x=x*x;  
}
while(! x); A, it is A loop B, it is A loop C, it is A loop D, there is A syntax errorCopy the code

Analytic:! The value of 1 is false, which means that it is time to execute the block if the body of the loop is false

For (I =1; i++<10; ) ; The value of the latter variable I is (C).

When to break out of the loop

A, 9 B, 10 C, 11 D, 10Copy the code

Resolution:

for(var i=1; i++<10;) { console.log(i)} console.log(i)//11 // 2 3 4 5 6 7 8 9 10 11Copy the code

19. What is not included in the keyboard event is (B).

【考 题 】

A, keydown B, keyover C, keypress D, keyupCopy the code

[C]Mouse events  Keyboard events

Keyboard events are triggered by the user hitting the keyboardkeydown,keypress,keyupThree events, they all inheritKeyboardEventInterface.

20, execute the following script statement on the page output (true).

【考 题 】 The comprehensive application of four operations and logical operations

var a=3;
a+=8*2;
alert(a>10&&a<=20);Copy the code

21, predict the output of the following code fragment var STR; (B)

alert(typeof str);

A; string B:undefined C:Object D:StringCopy the code

Which of the following is not a characteristic of Javascript?

C

Avascript is a scripting language. Avascript is event-driven. C. Avascript code must be compiled before executionCopy the code

JavaScript is a scripting language. Weak data type, object-based, event-driven language.

23. Read the following JavaScript code:

B

function f(y) {
    var x=y*y;
    return x;
}
for(x=0; x<5; x++) { y=f(x); document.writeln(y); } A.0 1 2 3 4 B.0 1 4 9 16 C.0 1 4 9 16 25 D. None of the above answers is correctCopy the code

(A) Array (b) array (C) array

An array is an array of different types. It is an array of different types.

A. The length of the array must be given at creation time and cannot be changed thereafter. B. Since the array is an object, you need to use the new operator C to create the array. D. Arrays can be initialized at the same time they are declaredCopy the code

25. Examine the following program snippets:

【考 题 】 The use of toFixed decimal places

var n = new Number(3456); alert(n.toFixed(2)); Is the following correct :(C) a. output 34 b. output 56 C. Output 3456.00 D. Output 345600Copy the code

26, Check the following program snippets.

If end is not specified, the slice() method selects all elements from start to the end of the array.

Var STR = "32 px"; var str1 = str.slice(-2); alert(str); alert(str1); A output "px" and "px" B output "32" and "32" C Output "32px" and "px" D Output "32px" and "32px"Copy the code

Parse: The slice method is used to extract a portion of the target array and return a new array, leaving the original array unchanged.

arr.slice(start, end);Copy the code

-2 indicates the second position in the reciprocal calculation, and -1 indicates the first position in the reciprocal calculation.

Click here to find out more aboutArray slice methodKnowledge.

27. Consider the following program snippets.

Indexof (indexof) : indexof (indexof) : indexof (indexof) : indexof (indexof)

Var STR = "12 px"; Var s = STR. Indexof (" 2 "); alert(s); A. Output 1 B. Output 2 C. Output P D. Output 12Copy the code

In JavaScript, which of the following code can execute expression(D) after 1 second?

(1 second is 1000 milliseconds) (1 second is 1000 milliseconds)

Aleem walji indow. SetTimeout (1000, expression); B.w indow. SetTimeout (expression, 1); C.w indow. SetTimeout (1, expression); D.w indow. SetTimeout (expression, 1000);Copy the code

Click here to find out more aboutThe use of the setTimeOut

29. In JavaScript, if a method is called directly without specifying the object, then the method belongs to the object by default:

Method calls are usually made to the window object if there is no explicit user.

A.document     B.Window   C.form    D.LocationCopy the code

30, select * from window where history belongs :(D)

【考 试 题 】

A.back(-1)    B.back(1)     C.forward(1)     D.go(-1)Copy the code

The window.history property points to the History object, which represents the browsing history of the current window.

// Return to the previous url history.back() // equivalent to history.go(-1)Copy the code

Click to see moreAbout history.

Var x=0; While (____) + x = 2;” To make the body of the while execute 10 times, the loop determination in the margin should be :(C)

A.x <10 B.x<=10 C.x<20 D.x<=20Copy the code

【考 题 】

The following () expression produces a random integer between 0 and 7 (including 0,7).

A.Math.floor(Math.random()*6)   
B.Math.floor(Math.random()*7)    
C.Math.floor(Math.random()*8)  
D.Math.ceil(Math.random()*8)Copy the code

Random number generation, pay attention to the left package right not package, random number will be often used in the future, need to master

33. If an HTML page contains code like the following, write a Javascript function to determine if the correct code is (C) to press enter on the keyboard.

【考 试 题 : keyCode = keyCode = keyCode

< input name = "password"typeOnkeydown = = "text""myKeyDown()">
A.   function myKeyDown() {if(window.keycode ==13) alert(" you hit the enter key "); B.function myKeyDown() {if(document.keycode ==13) alert(" you hit the enter key "); C.function myKeyDown() {if(event.keycode ==13) alert(" You hit the enter key "); D.function myKeyDown() {if (keyCode==13)
        alert("You hit enter.")
Copy the code

34. On an HTML page, a Javascript (D) event is triggered when any key on the keyboard is pressed

A.onFocus  B.onBlur C.onSubmit   D.onKeyDownCopy the code

The ++ operator is used to assign a value to a user. The ++ operator is used to assign a value to a user.

var x,y; X = 10; Y = x++; After running the above program, the value of the variable y is 10.Copy the code

The increment and decrement operators return the value of the variable before the increment and decrement operations. When placed before a variable, it increments/decrement and returns the value of the variable after the operation.

36, look at the following JavaScript program

var i,j; I = 0; J = I && (+ + I); After running the above program, the value of the variable I is 0.Copy the code

Resolution:

console.log(0&&1)//0Copy the code

Do while: Do while: do while: do while

var i; I = 8;do{                     
    i++;              
}
while(i>100); After running the above program, the value of the variable I is 9.Copy the code

38, look at the following JavaScript program.

for(var i=1; i<=10; i++){if(i==5) 
    continue;                     
    if(i==8) 
    break; alert(i); } run the above program, the pop-up dialog output values 1,2,3,4,6,7.Copy the code

Continue () continue () continue () continue ();

Write a program to remove duplicate elements from an array

【考 试 题 : Program logic, simple algorithm to achieve function, a problem many solutions 】

functionunique1(array){ var n=[]; // A new temporary array // iterate over the current arrayfor(var i=0; i<array.length; I ++){// If the ith of the current array is already in the temporary array, then skip it, otherwise push the current item into the temporary arrayif(n.indexOf(array[i])==-1) 
        n.push(array[i]);             
    }             
    return n;            
}Copy the code

40,

var k;       
for(var i=0; i<5; i++){for(var j=0; j<10 ; j++){ k=i+j; }} alert(k) //13forLoop, notice when to break out of the loop.Copy the code

K =4+9=13

41,

var a=0;       
test(a);function test(){              
    var a = 6              
    b()                
}       
function b(){alert(a)} = 0Copy the code

Alert (a) =0; alert(a) =0; alert(a) =0; alert(a) =0;

42,

function foo(){
    alert("aaaa");
    a = setTimeout(foo,100); } foo(); Infinite loop callCopy the code

SetTimeout and recursive calls

43. (A) method of the window object is used to pop up A confirmation dialog box that can be selected as “CONFIRM” or “Cancel”.

A, confirm() B, alert() C, prompt() D, open()Copy the code

解析 : confirm(” info “): a confirmation box appears (info, confirm button, cancel button);

Prompt (” prompt information “) : an input box appears, prompting the user to input information, not used in development;

Window. alert(Prompt information) : Displays information using the prompt function of the window.

Note: a) code execution after an alert blocks. B) the window. C) a newline for the alert message

Open A new window with the address ABC. HTML.

【考 题 : Open () method of BOM

A, window.open(" ABC. HTML ", ""," "); B, window.open(", ", "ABC", ""); C, window.open(" ", ""," ABC "); D, window. Open (", ", ");Copy the code

The window.open method is used to create another browser window, similar to the new window option in the browser menu. It returns a reference to the new window, or null if a new window cannot be created. The open method can take a total of three parameters.

window.open(url, windowName, [windowFeatures])Copy the code

  • url: a string representing the url of the new window. If omitted, the default url isabout:blank.
  • windowName: A string representing the name of the new window. If a window with the name already exists, the window is occupied and no new window is created. If omitted, it is used by default_blankTo create a new window without a name. There are also a couple of presets,_selfRepresents the current window,_topRepresents the top-level window,_parentRepresents the upper window.
  • windowFeatures: string containing comma-separated key-value pairs (see below) that indicate the parameters of the new window, such as whether there is a prompt bar, toolbar, and so on. If omitted, a new window with the full UI opens by default. If you create an existing window, this parameter does not take effect and the browser uses the parameters of the previous window.

More aboutPlease click to see the usage of window.open;

45, add comments to JavaScript programs by (AB) 【js comments 】

B, /* * * */ C, /* * */ D, /* * * *Copy the code

46, the following JavaScript variable names are illegal: (ABC)

A, 4Myvariable B, My@variable C,functionD, Myvariable4Copy the code

Resolution:

  • Variables are composed of letters, numbers, underscores, or the dollar sign $.
  • The first character can be a letter, an underscore, or the dollar sign $;
  • Subsequent characters can be letters, numbers, underscores, or dollar signs;

  • Variable names are case sensitive

  • Reserved words, keywords, JavaScript predefines many global variables and functions that cannot be used as custom variable and function names

  • Convention commonly known: identifier to see the name to know the meaning;
  • Hump nomenclature: Also known as lesser hump nomenclature. It is usually used to name variables, to explain and describe variables

    For example: var planeBulletSpeed; // The speed of an airplane bullet

47. Look at the following code. What does it output? (Variable declaration promotion)

var foo = 1;
function(){ console.log(foo); var foo = 2; console.log(foo); } Answer: output undefined and 2.Copy the code

What are the values of y and z? Two undefined

var x = 1;
var y = 0;
var z = 0;
function add(n){
    n=n+1;
}
y = add(x);
function add(n){
    n=n+3;
}
z = add(x);Copy the code

First, if there are two functions of the same name, the following function overwrites the previous one. Second, if a function returns no value, the output is undefined

49, write the result of function DateDemo, system time assumed today

function DateDemo(){  
    var d, s="Today's date is:";  
    d = new Date();  
    s += d.getMonth() +1 +"/";  
    s += d.getDate() + "/";  
    s += d.getFullYear();  
    returns; } console.log(DateDemo()) Result: Today's date is: current system dateCopy the code

Write the results of the program run?

for(i=0, j=0; i<10, j<6; i++, j++){  
    k = i + j;
}Copy the code

Result: 10 (Watch out for traps)

Write a program to flatalize the array and divide the repeated part of the data, and finally get an ascending and not repeated array

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];

The first method:

arr.toString().split(",").sort((a,b) => { return a - b}).map(Number)Copy the code

The second way:

Array.prototype.flat= function() {
    return[].concat(... this.map(item => (Array.isArray(item) ? item.flat() : [item]))); } Array.prototype.unique =function() {
    return [...new Set(this)]
}
const sort = (a, b) => a - b;
console.log(arr.flat().unique().sort(sort));Copy the code

The third way:

function spreadArr(arr=[]){
    if(arr.some(ele=>Array.isArray(ele))){
        let newArr = [];
        arr.forEach((ele) => {
            if(Array.isArray(ele)){ newArr = newArr.concat(... ele) }else{
                if(! newArr.includes(ele)) newArr.push(ele) } })return spreadArr(newArr);
    }
    return arr.sort((a,b)=> a-b);
}
spreadArr([ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]);Copy the code

The fourth way:

var arr = [2, -5, 6, [6, -5, [2, 5], [8, 10, [6, 8], -3], 2], 5];        
function f (arr) {            
    var newarr = [];            
    function fn (arr) {                
        for (var i = 0; i < arr.length; i++) {                    
            if (arr[i].length) {
                if(Array. IsArray (arr[I])) {fn(arr[I]); }else {
                    newarr.push(arr[i]);             
            }else{                        
                newarr.push(arr[i]);                    
            }                
        }            
    }            
    fn(arr);            
    return newarr;        
}        
var x = f(arr);        
var newarr = [];        
for(var n = 0; n < x.length; n++) {if (newarr.indexOf(x[n]) == -1) {               
        newarr.push(x[n]);           
    }        
}        
newarr.sort((a, b) => a - b)        
console.log(newarr)Copy the code

52. What are some basic specifications for writing JavaScript?

1. Do not declare multiple variables on the same line.

2. Please use ===/! == to compare true/false or numeric values

3. Use object literals instead of new Array

4. Do not use global functions.

5. The Switch statement must have a default branch

6. Functions should not sometimes return a value and sometimes not.

7. For loops must use braces

8. Curly braces must be used in If statements

9. Variables in for-in loops should be explicitly scoped using the var keyword to avoid scope contamination.

What is the difference between JS basic types and reference types?

Basic types: undefined, Boolean, number, string, NULL, symbol(ES6)

Reference types: object, arrary, the date, the RegExp (regular), the Function

Basic data types are simple data segments.

A reference type is an Object consisting of multiple values, all of which are instances of Object.

Basic types can be accessed directly, while reference types can be accessed according to the address of the object in memory, and then according to the address to obtain the value of the object, called reference access.

When assigning a value of a reference type from one variable to another, the value of the object stored in the variable is also copied into the space allocated for the new variable. When we talked about reference types earlier,

Stored in a variable is the address of the object in heap memory, so, unlike a simple assignment, the copy of the value is actually a pointer to an object stored in heap memory. So after the assignment,

If both variables hold the same object address, then both variables refer to the same object. Therefore, changing any of these variables will affect each other, causing a deep copy and a shallow copy of the object.

Can extend to ask how to deep copy.

Var, Let, const

Variables declared by var are mounted on window, while variables declared by let and const are not:

Var declares that variables are promoted, but let and const do not

Let and const declarations form the block scope

Let and const cannot declare variables of the same name in the same scope. Var can

Const 1. If assignment is mandatory, no null placeholder is allowed. 3. If you declare data of a compound type, you can modify its properties

55. What are the variable types? What are the primitive types (value types)? Is null an object?

Value type variables include Boolean, Null, Undefined, Number, String, and reference types include all of the Object class. Such as Date, Array, and Function. In parameter passing, value types are passed by value and reference types are passed by share.

In JS, there are six original values, which are:

  • boolean
  • null
  • undefined
  • number
  • string
  • symbol

First of all, primitive types store values and have no functions to call, such as undefined.toString().

At this point you must be wondering, this is not true, when ‘1’.tostring () can be used. In this case, ‘1’ is no longer the original type, it’s cast toString which is the object type, so we can call toString.

In addition to strong-turning the type if necessary, primitive types have some pitfalls

The number type of JS is floating point type, and it is used to meet some bugs, such as 0.1 + 0.2! == 0.3, but this will be covered in the advanced section. The string type is immutable, and no matter what method you call on the string, the value does not change.

In addition, for null, many people think it is an object type, which is not true. Although Typeof null does print object, this is a long-standing Bug in JS. In the original version of JS, the 32-bit system was used. For performance considerations, the type information of variables was stored in low order. The beginning of 000 represents an object, whereas null represents all zeros, so it was wrongly identified as object. Although the current inner class determination code has been changed, this Bug has persisted.

What is the difference between an object type and a primitive type? What happens when function arguments are objects?

In JS, all objects except primitive types are object types. Object types differ from primitive types in that primitive types store values and object types store addresses (pins). When you create an object type, the computer will open up a space in memory for the value, but we need to find that space, and that space will have an address (pointer).

const a = [];Copy the code

For constant A, assuming the memory address (pointer) is #001, the value [] is stored at address #001, and the constant A is stored at address (pointer) #001

const a = [];
const b = a;
b.push(1);Copy the code

When we will be variable assigned to another variable, replication is originally the address of the variable (needle), that is to say the current variable b store address (pointer) is # 001, when we modify the data will change in address (pointer) value in the history of # 001, has led to the two variables are changed.

Let’s look at the case where function arguments are objects

function test(person) {
    person.age = 26
    person = {
        name: 'yyy',
        age: 30
    }
    return person
};
const p1 = {
    name: 'yck',
    age: 25
};
const p2 = test(p1);
console.log(p1) // -> ?
console.log(p2) // -> ?Copy the code

For the above code, can you write the result correctly? Let me break it down for you:

  • First, the function pass argument is a copy of the pointer to the passed object
  • When you go inside the function and modify the properties of the parameters, as I’m sure you know, the current value of P1 is also changed
  • But there was a split when we reassigned an object to Person,

So person ends up with a new address (pointer) that has nothing to do with P1, resulting in the two variables having different values.

57, can typeof correctly determine the type? How does instanceof correctly identify objects?

For primitive types, the correct type can be displayed except for null

typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
Copy the code

Typeof displays objects except functions, so typeof does not accurately determine what type a variable is

typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'
Copy the code

If we want to determine the correct type of an object, we can consider using Instanceof because the internal mechanism is determined by the prototype chain, and we will implement an Instanceof ourselves in later chapters.

const Person = function() {}
const p1 = new Person()
p1 instanceof Person // true
var str = 'hello world'
str instanceof String // false
var str1 = new String('hello world')
str1 instanceof String // trueCopy the code

For primitive types, you can’t just use instanceof to determine the type, but there are ways to use instanceof to determine primitive types

class PrimitiveString {
static [Symbol.hasInstance](x) {
return typeof x === 'string'
}
}
console.log('hello world' instanceof
PrimitiveString) // trueCopy the code

If you don’t know what Symbol. HasInstance is, it’s just something that allows us to customize the behavior of instanceof. This code is equivalent to Typeof ‘hello world’ === ‘string’, So it’s true. This actually reflects a problem, instanceof is not 100% credible.

58, How to judge this? What’s this for the arrow function?

function a() {
    return() = > {return () => {
            console.log(this)
        }
    }
}
console.log(a()()())Copy the code

First of all, there is no “this” in the arrow function. The “this” in the arrow function depends only on the “this” in the first normal function that wraps the arrow function. In this case, because the first normal function wrapping the arrow function is a, this is window. In addition, using a function such as bind for the arrow function is invalid.

The last case is a context-changing API like bind. For these functions, this depends on the first argument. If the first argument is null, it is window.

So speaking of bind, have you thought about, if you bind a function multiple times, what’s the context?

let a = {}
let fn = function () { console.log(this) }
fn.bind().bind(a)() // => ?Copy the code

If you think the output is a, you’re wrong. We can actually convert this code to another form

/ / fn. The bind (). The bind is equal to (a)let fn2 = function fn1() {
    return function() {
        return fn.apply()
    }.apply(a)
}
fn2()
Copy the code

As you can see from the code above, no matter how many times we bind the function, this in fn is always determined by the first bind, so the result is always window.

let a = { name: 'yck' }
function foo() {
    console.log(this.name)
}
foo.bind(a)() // => 'yck'Copy the code

This is the rule for this, but it is possible for more than one rule to occur at the same time. In this case, the different rules will determine where this ends according to the highest priority.

First, new takes precedence, then bind, then obj.foo(), and finally foo. Once this is bound, it is not changed in any way.


JS advanced interview questions

What is your understanding of Ajax? (Concept, feature, function)

advantages

A, no plug-in support b, excellent user experience C, improve the performance of Web applications D, reduce the burden of server and bandwidth

disadvantages

(a) Lack of support for the XMLHttpRequest object in the browser. Almost all browsers now support the XMLHttpRequest object. (B) Break the normal function of the browser “forward” and “back” buttons, which can be remedied by simple plug-ins

2. What is cross-domain and how to implement cross-domain access?








Implementation: (1) JSONP cross-domain: using script script to allow reference to different domains under the JS implementation, the callback method into the server, return the result of the callback. (2) Cross-domain Resource Sharing (CORS) Cross-domain resource sharing (CORS) is a technical specification for Web browsers, which defines a way for Web servers to allow Web pages to access their resources from different domains. CORS is compared with JSONP: A, JSONP can only achieve GET requests, while CORS supports all types of HTTP requests. B. With CORS, developers can make requests and retrieve data using normal XMLHttpRequest, with better error handling than JSONP. C, JSONP is mainly supported by older browsers, which tend not to support CORS, while most modern browsers already support CORS.

3. What is the difference between GET and POST?

(1) Get is to obtain data from the server, post is to transmit data to the server. A GET request returns any information indicated by the request-URI. Post requests are used to send E-mail, news, or a form that can be filled out by an interactive user. This is the only request that needs to send the body in the request. When a Post request is used, the body Length must be specified in the Content-Length field of the packet header. (2) GET is to add the parameter data queue to the URL referred to by the ACTION attribute of the submitted form, and the value corresponds to each field in the form one by one, which can be seen in the URL. Post is an HTTP POST mechanism that places each field in the form and its contents in the HTML HEADER and sends it to the URL referred to by the ACTION attribute without the user seeing the process. (3) In get mode, the server uses Request.QueryString to obtain the value of the variable; in POST mode, the server uses Request. (4) The amount of data transmitted by GET is small and cannot be greater than 2KB. The amount of data transmitted by POST is large. Therefore, the default value is unrestricted. But theoretically, the maximum is 80KB for IIS4 and 100KB for IIS5. Filters that use IIS only accept get arguments, so most large search engines use GET. (5) Get security is very low, while POST security is relatively high. If the data is Chinese and non-sensitive, use GET; If the user enters data that is not Chinese characters and contains sensitive data, it is better to use POST.

4. Compare Flash and Ajax, which is better? How to choose between them in use?

Advantages of Ajax: (1) Searchable plain text web pages will be more conducive to SEO. The text content is easy for search engines to retrieve, but the tedious SWF bytecode is not desirable for search engines to touch. Although some large search engines such as Google can retrieve content within SWF, there is still a lot of trouble. (2), open Flash has been Macromedia for years to see very dead. Ancillary technologies such as Flex and FMS have always been expensive to install and maintain. JS has no such trouble. No one wants to take legal and copyright risks. Cost Flash development is expensive because environments such as FlashIDE are charged for. Ajax is different. There are some cheap tools for generating SWFS, but they simply can’t meet the complex requirements. (3) Ease of use Ajax applications have better ease of use. Because there is a Flash Player agent layer in the middle, many auxiliary functions cannot be flexibly utilized by Flash. And Flash has a bad rap in some ways. Such as pop-up ads, such as malicious code. (4) Easy to develop When people develop complex Ajax and Flash applications, will use some advanced development tools. In general, Ajax development kits are simpler and easier than Flash. Flash advantages: (1), multimedia processing Flash in audio, video and other multimedia fields compared to HTML has absolute advantages. Almost all websites now include Flash content. (2) Good compatibility: the only FlashPlayer “agent” is passed. You don’t have to debug a program in different browsers, as you do with JAVASCRIPT. This is Flash’s biggest advantage. SVG, Canvas Element and Direct can’t compete with Flash in this area. (4) Client resource scheduling Flash can more easily call external resources other than browsers. Such as cameras, microphones, etc. This, however, is something that normal HTML cannot do. But this may be a drawback (why?).

Disadvantages of Ajax: (1) it can break the browser’s back feature, (2) using dynamic page updates makes it difficult for users to save a particular state to favorites, but there are solutions to these. Disadvantages of Flash: (1) Binary format; (2) Private format; (3) Flash files are often large and require long wait times when users first use them; and (4) performance issues

5. What’s the difference between synchronous and asynchronous?

An example: normal B/S (synchronous) AJAX (asynchronous)

Sync: Submit the request -> wait for the server to process it -> return the client browser cannot do anything during this period

Asynchronous: Requests are triggered by events -> server processing (this is where the browser can still do other things) -> processed

In the ajax.open method, the third parameter is set to synchronous or asynchronous.

Js libraries such as Prototype default to asynchronous, which is set to true. In the case of synchronization, js waits for the request to return and gets the status. The onReadyStatechange event handler is not required. Asynchronous requires onReadyStatechange event handling with a value of 4 before handling the following correctly.

// Synchronous transmission modefunction RequestByGet(nProducttemp,nCountrytemp) { 
    var xmlhttp 
    if (window.XMLHttpRequest) { 
         //isIE = false; 
         xmlhttp = new XMLHttpRequest(); 
    }else if (window.ActiveXObject) { 
         //isIE = true; 
        xmlhttp = new  
        ActiveXObject("Microsoft.XMLHTTP"); 
    }             
    //Web page location.      
    var URL="http://www.baidu.com/; xmlhttp.open("GET",URL, false); //xmlhttp.SetRequestHeader("Content-Type","text/html; charset="utf-8") 
    xmlhttp.send(null); 
    var result = xmlhttp.status; 
    //OK 
    if(result==200){ 
       document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText; 
    } 
    xmlhttp = null; 
}Copy the code

// Asynchronous transport mode var XMLHTTPfunction RequestByGet(nProducttemp,nCountrytemp) { 
    if (window.XMLHttpRequest) { 
         //isIE = false; 
         xmlhttp = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
         //isIE   =  true; 
         xmlhttp  =   new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
                
    //Web page location. 
    var URL="http://www.baidu.com/"; 
    xmlhttp.open("GET",URL, true); 
    xmlhttp.onreadystatechange = handleResponse; 
    //xmlhttp.SetRequestHeader("Content-Type"."text/html; charset=UTF-8") 
    xmlhttp.send(null); 
} 

function handleResponse() { 
    if(xmlhttp.readyState == 4 && xmlhttp.status==200) { 
       document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText; xmlhttp = null; }}Copy the code

6. According to your understanding, please brief the implementation principle of JavaScript script?

JavaScript is a dynamic, weakly typed, prototype-based language that can be executed directly by the browser. When the browser encounters a

7. What is your understanding of JSON?

Answer a:

JSON(JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript. The data format is simple, easy to read and write, and consumes little bandwidth. Json simply means objects and arrays in javascript, so these two structures are objects and arrays. A. JSON object: starts with {and ends with}, and contains a series of key value pairs. Keys and values are separated by commas (:), and each pair is separated by commas (,). Refer to the following syntax structure: {key1: value1, key2, value2, key3: value3… } A key is a string, and a value can be a string, a number, true,false,null, an object, or an array. But it’s easy to tell by reference to these understandings. B, JSON array: For example, C#, Button[] btnArray, btnArray is an array of type Button, and it contains the object of type Button, so is the JSON array, which contains the JSON object.

Answer two: A) JSON refers to the JavaScript Object Notation. B) JSON is a lightweight text data interchange format and is not a programming language. C) JSON exists independently of the language. JSON can transform a set of data represented in a JavaScript object into a string that can then be easily passed between functions or from a Web client to a server-side program in an asynchronous application. This string looks a little odd, but JavaScript can easily interpret it, and JSON can represent more complex structures than “name/value pairs.” For example, you can represent arrays and complex objects, not just simple lists of keys and values

8. What do you think of closures?


(2) Closures have three features:






9. What is your understanding of This object?

(1) The “this” point in js is uncertain, which means it can be changed dynamically. Call /apply is used to change the function that this refers to. This design makes the code more flexible and reusable. (2) This is usually the owner of the function that refers to it. (3) In function self-execution, this refers to the window object. A) use the tag attribute to register the event. In this case, this refers to the Window object. To make this point to input, you can pass this as an argument. C. Use addEventListener to register events. This is also pointing to input.

Answer two:

(1) this in global scope: this defaults to the window object in global scope.

this; /*window*/ var a = {name:this}/*window*/ var b =[this]; /*window*/Copy the code

(2) In this function, there are several cases:

A, normally defined function, and then normally executed: this still defaults to window.

var a = function(){ console.log(this); } a(); /*window*/Copy the code

B, a general definition, executed with a new call: let this point to the newly created empty object, then we can initialize our own variables to the empty object

var a = function(){ console.log(this); } new a(); /* Create an empty object */Copy the code

C, when a function is called as an object property: this refers to the object a that called f.

var a = {
    f:function(){ console.log(this) } } a.f(); / * * / a objectCopy the code

(3) Change the default reference to this with call() and apply() :

var b = {id: 'b'};
var a = {
    f:function(){console.log(this)}} a.f.call(b); //{id:"b"}Copy the code

All function objects have call and apply methods, and their usage is roughly similar. F.call (b) means that the function f is executed and this in the active object refers to b, so that when the identifier is resolved, this will be b. But to call a function, you have to pass parameters. So, f.call(b, x, y); f.apply(b, [x, y]); This is the difference between the call method and the apply method: the apply method passes the parameters as an array, and the call method passes the parameters as a parameter.

(4), some special execution of this function point problem:

A, setTimeout() and setInverval():

var a = function(){
    console.log(this);
}
setTimeout(a,0); /*window*/Copy the code

SetInterval ().

B. This in the live object in the callback method execution that triggers the event in the DOM model points to the DOM object.

10. How many ways can JavaScript objects be created?

(1) Using the new method

var obj = new Object(); Copy the code

(2) Factory mode

function Parent(){
    var Child = new Object();
    Child.name="Tears like snow.";
    Child.age="20";
    return Child;
};
var x = Parent()Copy the code

Var x = new Parent(); var x = new Parent(); Because of the potential problems with the former (also known as the classic factory approach; the latter is called the hybrid factory approach), it is not recommended to use the object in the new way

(2) Constructor mode

function Parent{(). This name ="Tears like snow."; this.age="20";
};
var x =new Parent();Copy the code

(3) Prototype mode

function Parent() {}; Parent.prototype.name="Tears like snow.";
Parent.prototype.age="20";
var x =new Parent();Copy the code

(4) Mixed constructors, prototype style (recommended)

function Parent{(). This name ="Tears like snow."; this.age=22; }; Parent.prototype.lev=function() {return
    this.name;
};
var x =new Parent();Copy the code

(5) Dynamic prototype

function Parent{(). This name ="Tears like snow."; this.age=22;if(typeofParent._lev=="undefined"){
        Parent.prototype.lev=function() {return this.name;
    }       
    Parent._lev=true;    
}}
var x =new Parent();Copy the code

11. Please write down the js memory leak problem?

(1), IE7/8 DOM object or ActiveX object circular reference caused memory leak a, multiple objects circular reference b, circular reference itself (2), basic DOM leakage When the original DOM is removed, the child node reference is not removed can not be recycled. A memory leak refers to any object that exists after you no longer have it or need it. The garbage collector periodically scans objects and counts the number of other objects that reference each object. If the number of references to an object is zero (no other object has referenced the object), or if the only reference to the object is circular, then the object’s memory can be reclaimed. Using a string instead of a function as the first argument to setTimeout causes a memory leak. Closures, console logs, and loops (which occur when two objects reference each other and keep each other) can also cause memory leaks.

12. Would you please explain the event bubbling mechanism?

A, trigger certain events on an object, such as click onclick event), if the object defines a handler for this event, this event will call the handler, if does not define the event handler returns true or events, the event is transmitted to the object’s parent object, from the inside out, Until it is processed (all similar events are activated for the parent object), or it reaches the very top level of the object hierarchy, the Document object (some browsers are Windows). B. Bubbling events: Events are triggered in order from the most specific event target to the least specific event target (document object). The bubble mechanism of C and JS refers to that if an element defines event A, such as click event, if the event is triggered and the bubble event is not blocked, then the event will be propagated to the parent element, triggering the click function of the parent class.

// Stop the bubble time method, compatible with IE (E.Canclebubble) and FF (E.topprogation)

functionstopBubble(e){ var evt = e||window.event; evt.stopPropagation? evt.stopPropagation():(evt.cancelBubble=true); // prevent bubbles evt. PreventDefault}Copy the code

Tell me your understanding of Promise.

ES6 provides Promise objects natively. A Promise is an object used to deliver messages for asynchronous operations. It represents some event (usually an asynchronous operation) whose outcome is known in the future, and it provides a uniform API for further processing. A Promise object has two characteristics. (1) The state of the object is not affected by the outside world. A Promise object represents an asynchronous operation that can be in three states: Pending, Fulfilled, or Rejected. Only the result of an asynchronous operation can determine the current state, which cannot be changed by any other operation. That’s where the name “Promise” came from, meaning “Promise” in English, meaning it can’t be changed by other means. (2) Once the state changes, it will not change again, and this result can be obtained at any time. The state of a Promise object can change from Pending to Resolved and from Pending to Rejected. So as long as these two things happen, it’s frozen, it’s not going to change anymore, it’s going to stay that way. If you add a callback to a Promise object even after the change has occurred, you get this result immediately. This is completely different from events, which have the characteristic that if you miss it and listen again, you don’t get the result.

With Promise objects, you can express asynchronous operations as synchronized operations, avoiding layers of nested callbacks. In addition, Promise objects provide a uniform interface that makes it easier to control asynchronous operations.

Promise also has some downsides. First, there is no way to cancel a Promise. Once a Promise is created, it is executed immediately. Second, if the callback function is not set, the errors thrown by the Promise internally are not reflected externally. Third, when you are in the Pending state, you have no way of knowing where you are (just started or about to finish).

What do you know about Javascript garbage collection?

This is the most common garbage collection method of ‘JavaScript’. When a variable enters the execution environment, such as declaring a variable in a function, the garbage collector marks it as “entering the environment”. When a variable leaves the environment (the end of function execution), it is marked “out of the environment.” At runtime, the garbage collector marks all variables stored in memory, and then removes variables in the environment and variables referenced by the environment variables (closures). Variables that remain marked after this is done are those to be deleted

Memory leaks often occur in early versions of ‘IE’, which is often because reference counting is used for garbage collection. Reference counting strategy is to track the number of each value is used, when declaring a variable and will be a reference type assigned to the variable when the value of the reference number is, if it is the value of a variable into another, this is worth reference number minus 1, when the value of citations to 0, show that no variables in use, The value can no longer be accessed, so the space occupied by it can be reclaimed, so that the garbage collector will clean up the space occupied by the zero reference value at run time. In IE, although ‘JavaScript’ objects are garbage collected by token clearing, BOM and DOM objects are garbage collected by reference counting. That is to say, as long as BOM and DOM are involved, circular reference problems will occur.

15. What is your understanding of prototype?

JavaScript is a prototype-based inheritance language that is different from other high-level languages, like Java and C#, where inheritance is determined by type. JavaScript is a dynamically weakly typed language. In short, you can think of everything in JavaScript as objects. A prototype is also an object. It is possible to inherit an object’s properties through a stereotype. JavaScript objects contain an internal property called “prototype” that corresponds to the object’s prototype.

“Prototype” is an internal property of an object and cannot be accessed directly. So in order to look at the prototype of an object, The “__proto__” nonstandard accessor is provided in the JavaScript engine of the Firefox and Chrome kernel (the new ECMA standard introduces the standard Object prototype accessor “object.getPrototype (Object)”).

The main purpose of a stereotype is to implement inheritance and extension objects.

16. What is the difference between typeof and instanceof?

In JavaScript, you can determine the typeof a variable by using typeof (1), a number type, and the value returned by typeof is number. For example, typeof(1) returns number (2), a string type, and typeof returns string. For example, typeof(“123”) returns a string. (3) Boolean type. The value returned by typeof is Boolean. For example, typeof(true) returns a Boolean. (4), object, array, null return value is object. For example, typeof(window), Typeof (document), and Typeof (null) return values that are objects. (5) Function type, return value is function. For example, both typeof(eval) and Typeof (Date) return functions. (6) If a variable, function, or undefined does not exist, undefined is returned. For example, typeof(ABC), typeof(undefined) both return undefined. In JavaScript,instanceof is used to determine whether an object was constructed by another function. One problem with using the typeof operator to store values with reference types is that it returns “object” regardless of the typeof object being referenced. ECMAScript introduces another Java operator, Instanceof, to address this problem. The instanceof operator is similar to the typeof operator to identify the typeof object being processed. Unlike the Typeof method, the Instanceof method requires the developer to explicitly confirm that the object is of a particular type.

17. Describe briefly your understanding of Javascript object-oriented?

In order to demonstrate that JavaScript is a thorough object-oriented language, it is necessary to start with the concept of object orientation. , everything all object b, c, encapsulation and inheritance characteristics object and using the message communication between objects, their existence information hidden in these three points as the basis, the c + + is object-oriented and procedural language, because, although he realized class encapsulation, inheritance and polymorphism, but the nature of the existence of the object, the global functions and variables. Java and C# are fully object-oriented languages that organize functions and variables in the form of classes so that they cannot exist apart from objects. But here the function itself is a process, just attached to a class. However, object-oriented is only a concept or programming idea, and it should not be dependent on a particular language. For example, Java uses object-oriented ideas to construct its language, it implements the class, inheritance, derivation, polymorphism, interface and other mechanisms. But these mechanisms are only a means of implementing object-oriented programming, not a necessity. In other words, a language can choose the right way to implement object orientation according to its nature. Therefore, since most programmers first learn or use advanced compiled languages such as Java and C++ (although Java is half compiled and half interpreted, it is generally explained as compiled), they preassume the object-oriented implementation of “class”. Therefore, when learning scripting languages, It is customary to use the concepts in a class-based object-oriented language to determine whether the language is object-oriented or whether it has object-oriented characteristics. This is one of the main reasons that prevents programmers from learning and mastering JavaScript in depth.

The JavaScript language implements object-oriented programming through a method called prototype. In the following sections, we will discuss the differences in the way in which the objective world is constructed between class-based object-oriented and prototype-based object-oriented.

The class-based object-oriented approach is compared with the prototype-based object-oriented approach. In the class-based object-oriented approach, objects are generated by classes. However, in the prototype-based object-oriented approach, objects are constructed by relying on constructor and using prototype. Take an example of the objective world to illustrate the difference between these two ways of knowing. For example, when a factory builds a car, on the one hand, the worker must refer to an engineering drawing to design how the car should be built. The engineering drawing here is like the class in the language, and the car is built according to this class. On the other hand, worker and machine (constructor) construct the car using various parts such as engine, tires, steering wheel (various properties of prototype). In fact, there is a debate as to which of the two approaches expresses object-oriented ideas more thoroughly. But think that the original type of object-oriented is a more complete object-oriented way, for the following reasons: (1), first of all, the object appears in the objective world of all are the result of other physical objects structure, and abstract “drawings” is not “car”, that is, not the entity class is an abstract concept, but the object is an entity of production; (2) Secondly, in accordance with the most basic object-oriented principle that everything is an object, a class is not itself an object, while its constructor and prototype are themselves objects constructed by other objects through the prototyping method. (3) Third, in class-based object-oriented languages, the state of an object is held by its instance, and its method is held by the class that declares it. Only the structure and methods of the object can be inherited. In the original type object-oriented language, the behavior and state of the object belong to the object itself, and can be inherited together (reference resources), which is more close to the objective reality. (4) Finally, class-based object-oriented languages such as Java compensate for the lack of access to global functions and variables found in procedural languages by allowing classes to declare static properties and static methods. In fact, there is no so-called static concept in the objective world, because everything is an object! In the original object-oriented language, except for build-in objects, global objects, methods, or properties are not allowed, and there is no concept of static. All language elements (primitives) must depend on the existence of the object. However, due to the nature of functional languages, the objects that language elements depend on change with the runtime context, which is embodied in the change of this pointer. It is this characteristic that is closer to the nature that “everything belongs to everything, and the universe is the foundation of everything’s existence”

18. What is your understanding of JavaScript functions?



Functions in javascript are objects, which are collections of “key/value” pairs that have a hidden connection to the stereotype pair.

The first function has a default object called Arguments. This object looks like an array, but is not an array. This object is the argument passed to the function. In javascript, an object constructor can create an object. (3) function call a: call a method on an object, replace the current object with another object b: apply a method on an object, replace the current object with another object, similar to call. C, Caller: When a function calls another function, the called function automatically generates a caller attribute that points to the calling function object. If the function is not currently called or is not called by another function, then caller is null. D, Callee: When the function is called, its arguments. Callee object refers to itself, i.e. a reference to itself.

19. What is the IIFE? What does it do?

IIFE, that is, Immediately-Invoked Function Expression. The execution parentheses of the Immediately Invoked Function Expression should be written inside the hyphen. Although writing in or out is valid, writing in makes the whole expression look more like a whole, so it is recommended.

// The two most common ways to write (function(){ /* code */ }()); // Teacher recommended writing (function(){ /* code */ })(); That / / / / brackets and JS some operators (such as = && | |, etc.) can disambiguate on function expression and function declarations / / the following code, the parser already know is an expression, and also put another default to expression / / but both exchange would be an error var I =function() {return10; } ();true && function(){ /* code */ }(); 0,function(){ /* code */ }(); // If you're not afraid of obscure code, you can also choose unary operators!function(){ 
    /* code */ 
}();
~function(){
    /* code */ 
}();
-function(){ 
    /* code */ 
}();
+function(){ /* code */ }(); // You can also do newfunction(){ /* code */ }
new function(){/* code */}() // ParameterCopy the code

IIFE functions (1) : Improve performance: reduce scope lookup time. One small performance advantage of using IIFE is that common global objects such as Window, Document, and jQuery are referred to in scope by passing the parameters of anonymous functions. The JavaScript interpreter looks for properties first in scope and then all the way up the chain until it reaches global scope. Putting global objects in the IIFE scope improves the js interpreter’s lookup speed and performance. (2) Compress space: pass global objects as arguments, and these global objects can be anonymously compressed into a more compact variable name. (3) Avoid conflicts: anonymous functions can form a block-level private scope inside. (4) Dependency loading: Flexible loading of third-party plug-ins, of course, using modular loading is better (AMD,CMD)

20. What is your understanding of Function and Object?

A Function is an object, and an object representing a Function is a Function object. All Function objects are constructed from the Function object. Function is the top-level constructor. It constructs all objects in the system, including user-defined objects, built-in objects, and even itself. This also indicates that Function is bootled-out (the ability to construct itself). This indirectly determines that the call and constructor logic of the Function are the same. Each object has a constructor property that points to the function object that created it. A, function and Object have the same language status B, there is no class, only Object C, function is also an Object, so called function Object d, Object is passed by reference to Object, it is the highest level of Object, all objects will inherit the prototype of Object, But you also need to know that Object is also a Function Object, so Object is constructed by Function.

21. JavaScript prototype chains



22. Can you tell the difference between native objects, built-in objects, and hosted objects in JavaScript?

Ecma-262 defines native objects as “objects provided by ECMAScript implementations independent of the host environment.” Take a look again at what “local objects” contain: Object, Function, Array, String, Boolean, Number, Date, RegExp, Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError As you can see, the local object is simply the class (reference type) defined by ECMA-262. Built-in Objects ECMA-262 defines a built-in object as “any object provided by an ECMAScript implementation that is independent of the host environment and occurs when an ECMAScript program begins execution.” This means that the developer does not have to explicitly instantiate the built-in object; it has already been instantiated. Again, “independent of the host environment.” By definition it seems difficult to distinguish between “built-in objects” and “local objects.” Ecma-262 defines only two built-in objects, Global and Math (which are also local objects, and each built-in object is a local object by definition). That makes sense. Built-in objects are a type of local object. Of the two objects it contains, the Math object is often used, but what is this Global object? The Global object is the most special object in ECMAScript because it doesn’t exist, but remember that in ECMAScript, there are no independent functions. All functions must be methods of an object. Methods like isNaN(), parseInt(), and parseFloat() all look like functions, but in fact they are methods of Global objects. (3) Host Objects Objects provided by ECMAScript’s host environment, that is, our web page’s running environment (operating system and browser). All BOM and DOM are host objects. Global methods provided by the host environment: Built-in objects are a type of local objects, which are officially defined, while host objects are equivalent to self-defined objects, DOM objects, and BOM objects

23. Please explain the variable declaration promotion?

A, variable definition can use var to define a variable. If there is no value assigned to the variable, the initial value of the variable is undefined. B. Variable Scope A variable scope refers to the scope within which a variable functions. Variables are divided into global variables and local variables. Global variables are defined globally; Local variables are valid only within a function. Within the function body, local variables or arguments with the same name take precedence over global variables. That is, if the function has a local variable or parameter with the same name as the global variable, the global variable will be overwritten by the local variable. All variables not defined using var are treated as global variables.

24. Avoid the problem of using the same name for multiple javascript development functions

Namespace closed space JS modularized MVC (data layer, presentation layer, control layer) SEAJS variables converted into object property objectification

25. Inheritance implementation in javascript Object-oriented

function Person(name){
        this.name = name;
}

Person.prototype.showName = function(){
        alert(this.name);
}

function Worker(name, job){
       
Person.apply(this,arguments)
        this.job = job;
}
for(var i in Person.prototype){
        Worker.prototype =
Person.prototype;
}
new Worker('sl'.'coders').showName();Copy the code

26. Write three typical applications that use this

Event: such as onclick this-> event occurs in the object constructor this->new out of the object call/apply change this

27. How can you optimize your code?

Code reuse avoids global variables (namespaces, closed Spaces, modular MVC..) Splitting functions prevents functions from being over-commented

28. Explain how AJAX works as thoroughly as possible

1) create ajax object (XMLHttpRequest/ActiveXObject (Microsoft. XMLHttp)) 2) judgment data transmission way (GET/POST) 3) open the link to the open () 4) send the send (), 5) When the Ajax object completes the fourth step (onreadyStatechange), the callback function is executed to determine the HTTP response status (status) between 200 and 300 or 304 (cache)

How to understand event delegate in JS

Specifically, event delegate is when the event target does not handle the event itself, but delegates the processing task to its parent or ancestor element, or even the root element (document). JQuery provides.bind(),.live(), and.delegate() methods for binding and delegate events

1.. Bind () can only bind events to elements that already exist when it is called, but not to future elements. Live () or.delegate() should be used instead of.

2. Bind the same event to many elements in the DOM;

3. Bind events for elements that do not yet exist in the DOM;

30. What’s the difference between call and apply?

The apply: method can hijack the methods of another object and inherit the properties of another object.

The Function. Apply (obj,args) method can take two arguments

Obj: This object will replace this object in the Function class

Args: this is an array that will be passed as arguments to Function (args–>arguments)

Call: The same as apply, but with a different argument list.

Function call (obj, [param1 [, param2 [paramN], […]]])

Obj: This object will replace this object in the Function class

Params: This is a list of parameters

In the case of object arguments, if arguments are of array type, such as arguments passed in the Apply example, the argument is of array type, and the argument list is the same when calling Person (that is, the first two arguments are the same for Person and Student). I can apply, If my argument list for Person looks like this (age,name), and my argument list for Student looks like this (name,age,grade), then I can implement this with call, which is to directly specify the location of the argument list values (person.call (this,age,name, grade));

Some other clever uses of apply

When I call the apply method, the first argument is an object (this), and the second argument is a collection of arrays, so when I call Person, he doesn’t need an array, but why does he give me an array and I can still parse the array into arguments,

[param1,param2,param3] [param1,param2,param3] [param1,param2,param3] [param1,param2,param3] It would take a while to implement a program that would replace each item in an array with a list of parameters. This feature of Apply makes this efficient:

31. What do A, B and C output respectively?

function fun(n,o) { 
    console.log(o) 
    return {    
        fun:function(m){      
            returnfun(m,n); }}; } var a = fun(0); a.fun(1); a.fun(2); a.fun(3); var b = fun(0).fun(1).fun(2).fun(3); var c = fun(0).fun(1); c.fun(2); c.fun(3); //undefined, 0, 0, 0 //undefined, 0, 1, 2 //undefined, 0, 1, 1Copy the code

32. What does this output?

<ul id="test""> < span style =" max-width: 100%; clear: both; min-height: 1em; Word-wrap: break-word! Important; "> < span style =" max-width: 100%; < span style = "max-width: 100%; clear: both; min-height: 1em; </li> </ul> <scripttype="text/javascript">
  var elements = document.getElementById('test').querySelectorAll('li');
  for (var i = 0; i < elements.length; i++) {
    elements[i].onclick = function() {alert (I); < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; white-space: normal;Copy the code

33. Read the program to the results:

function A() {}function{B (a) enclosing a = a; }functionC(a){if(a) {enclosing a = a; }} a.rototype. a = 1; P. rototype. A = 1; C.p rototype. A = 1; The console. The log (new A (). A); The console. The log (new B (). A); console.log(new C(2).a); Results: 1, undefined, 2.Copy the code

34. The topic is

var F = function() {}; Object.prototype.a =function() {}; Function.prototype.b =function() {}; var f = new F();Copy the code

Q: Does calling f.a() and f.b() work?

Answer: you can call f.a() but not f.b();

35. There was a cute little dog (named “Puppy”) who had a nice bark (wow) and would yelp every time he saw his owner (Yelp). Another puppy was very energetic (named Energetic Dog) and gave a yelp (Wow) every five seconds.

Use the object - oriented hybrid mode to achieve the creation of the dogfunction Dog() {    
    this.name = 'Puppy dog';    
    this.wow = 'wow';
}
Dog.prototype.yelp = function() {    
    console.log(this.wow);
} 
function MadDog() {    
    Dog.call(this);   
    this.name = 'Energetic dog';
}
for (var i in Dog.prototype) {    
    MadDog.prototype[i] = Dog.prototype[i];
};
MadDog.prototype.yelp = function () {    
    var _this = this;    
    setInterval(function(){        
        console.log(_this.wow);    
    }, 5000);
}
var dog = new MadDog();
dog.yelp();Copy the code

36. What do I know about HTTP status codes?

100 Continue This message is returned after the HTTP header has been sent. The server then sends the parameter information

200 OK A normal message is displayed

201 Created The request succeeds and the server creates a new resource

202 Accepted The server Accepted the request but has not yet processed it

301 Moved Permanently to a new location.

302 Found Temporary redirection.

303 See Other Temporary redirects and always requests a new URI using GET.

304 Not Modified The requested page has Not been Modified since the last request.

400 Bad Request The server does not understand the format of the Request. The client should not attempt to make the Request again with the same content.

401 Unauthorized Requests Are not authorized.

403 Forbidden Forbidden access.

404 Not Found Failed to find how to match the resource URI.

500 Internal ServerError Indicates the most common server – side error.

503 Service Unavailable The server is temporarily unable to process the request (possibly due to overload or maintenance).

37. What are your front-end performance optimization methods?

(1) reduce the number of HTTP requests: CSSSprites, JS, CSS source compression, image size control appropriate; Web pages Gzip, CDN hosting, data cache, image server.

(2) Make Ajax cacheable, front-end template JS+ data, reduce the bandwidth waste caused by HTML tags, front-end variables to save ajax request results, each operation of local variables, no request, reduce the number of requests

(3) Use innerHTML instead of DOM operations to reduce DOM operations and optimize javascript performance.

(4) When there are many styles to set, set className instead of style.

(5) Use less global variables and cache the search results of DOM nodes. Reduce IO read operations.

(6) Avoid CSSExpression, also known as Dynamic Properties.

(7) Preload the image, place the stylesheet at the top (CSS using the tag at the top), and place the script at the bottom with a timestamp.

(8) Proper use of HTTP caching

(9) JS removes duplicate scripts

(10) Optimize the image and try to use PNG

(11) Load components lazily

(12) Reduce the number of DOM elements

38. What common operations cause memory leaks?

A memory leak is any object that persists after you no longer have it or need it.

The garbage collector periodically scans objects and counts the number of other objects that reference each object. If the number of references to an object is zero (no other object has referenced the object), or if the only reference to the object is circular, then the object’s memory can be reclaimed.

Using a string instead of a function as the first argument to setTimeout causes a memory leak.

Closures, console logs, loops (a loop occurs when two objects reference each other and keep each other).

39. Read the program:

 (function() { var a = b = 5; }) (); console.log(b); Answer: 5Copy the code

40. Execute this code and output what result.

function test() {       
    console.log(a);     
    console.log(foo());       
    var a = 1;    
    function foo() {          
        return2; }}test(a);Copy the code

The result of this code is undefined and 2.

41. What does the following code output? Give your answer.

var fullname = 'John Doe';   
var obj = {      
    fullname: 'Colin Ihrig',      
    prop: {         
        fullname: 'Aurelio De Rosa',        
        getFullname: function() {           
            returnthis.fullname; }}}; console.log(obj.prop.getFullname()); vartest = obj.prop.getFullname;  
console.log(test()); The answer is Aurelio De Rosa and John Doe.Copy the code

42. How do I prevent event bubbles and default events

e. stopPropagation(); // Standard browsers prevent event bubble event.cancebubble =true; // Ie9 blocked default events before: in order not to let a click on the jump, we need to block his click on the eventreturn
falsee.preventDefault();Copy the code

43. What exactly does the new operator do?

1, create an empty object, and this variable refers to the object, while inheriting the prototype of the function.

2. Properties and methods are added to the object referenced by this.

3, the newly created object is referenced by this and implicitly returns this.

44. It is common to see javascript and CSS files loaded with parameters in the page. What is the purpose of doing this? (Answer from Baidu)

(1) Version Settings

(2) Mainly to avoid caching, each time after modifying the CSS file, re-reference the parameters after the change, so that the file will be re-requested, will not use the cache.

(3) to control the loading order of an external JS or CSS file

Async indicates to load the script immediately

Defer means that the script can be loaded lazily until the entire page has loaded before loading the JS or CSS. The goal is to control the inclusion sequence

45. Describe how browsers load and render? (Answer from Baidu)

(1) The order of Internet Explorer download is from top to bottom, and the order of rendering is also from top to bottom. Download and rendering are carried out simultaneously

(2) By the time you render to a section of the page, all of the above sections have been downloaded (not that all associated elements have been downloaded);

(3) In the process of downloading, if a tag is an embedded file, and the file is semantic interpretative (for example: JS script, CSS style), then IE download process will enable a separate connection to download, and in the download after parsing, parsing (JS, CSS if there is a redefinition, after the definition function will override before the definition function) process, stop the page all the next elements download;

46. How do you manage all the CSS files, jS, and images on a large, heavily visited website?

Answer: It involves manpower, division of labor, synchronization

(1) The advance team must determine the global style, coding pattern, etc

(2) Writing habits must be consistent

(3) Annotate the style writer, and timely annotate each module (annotate the key style invocation place)

(4) Page annotation

(5) Css and HTML folder parallel storage, naming should be unified

(6) Js sub-folder storage, named with the Js function shall prevail in English translation

(7) The picture adopts the integrated. PNG format file, try to integrate together, convenient management in the future

47. What is shockproof and throttling? What’s the difference? How?

Anti-shaking: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within N seconds, the time is recalculated

Idea: Cancel the delay in calling the method each time the event is triggered

function debounce (fn) {
    lettimeout = null; // Create a tag to hold the return value of the timerreturn function() { clearTimeout(timeout); // Whenever the user enters the previous onesetTimeout Clear Off Timeout =setTimeout(() => {// then create a new oneset// Fn function fn. Apply (this, arguments) will not be executed if there are still characters to be entered; }, 500); }; }function sayHi() {
    console.log('Stabilized successfully');
}
var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi)); / / image stabilizationCopy the code

Throttling: High frequency events are triggered, but only once in n seconds, so throttling will dilute the frequency of function execution

Each time an event is triggered, it determines whether there is a delay function waiting to be executed

function throttle(fn) {
    let canRun = true; // Save a tag by closurereturn function () {
        if(! canRun)return; // At the beginning of the function, check whether the tag istrue, not fortruethereturn
        canRun = false; // Immediately set tofalse
        setTimeout(() => {// put the execution of the externally passed function insetThe Timeout of fn. Apply (this, the arguments); / / in at lastsetTimeout is executed before setting the tag totrue(Key) indicates that the next loop is ready to execute. // The marker is always when the timer is not executedfalseIn the beginningreturnOff canRun =true;
        }, 500);
    };
}
function sayHi(e) {
    console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));Copy the code

48. Talk about Http caching policies

Http caching is controlled by two fields in the header:

Cache-control contains several fields:

Private: Only the client can cache

Public: Both the client and proxy server can cache

Max-age: indicates the expiration time of the cache

No-cache: Comparison cache is required to verify cached data

No-store: No memory will be cached

ETag: Used for comparison cache. An ETag is an identifier of a server resource

When the client sends the first request, the server sends the Etag of the current resource. When the client sends the next request, the client carries the Etag with the if-none-match in the header. The server compares the Etag sent by the client with the latest resource Etag. If yes, the resource was not updated and 304 is returned.

The Http caching mechanism is realized by the combination of cache-control and Etag.


jQuery:

1. What is your understanding of deferred?

Deferred objects are a new feature introduced with jQuery 1.5.0. When developing web sites, we often encounter javascript operations that take a long time. There are both asynchronous operations (such as ajax reading server data) and synchronous operations (such as traversing a large array), neither of which have immediate results. It is common practice to specify callback functions for them. Specify in advance which functions should be called once they have finished running. However, jQuery is very weak when it comes to callbacks. To change this, the jQuery development team designed the Deferred object. Simply put, deferred objects are jQuery’s callback solution. In English, defer means “to defer,” so the Deferred object means to “defer” execution until some point in the future. It addresses the issue of how to handle time-consuming operations, provides better control over those operations, and provides a unified programming interface. B. Its main functions can be summed up as four points: (1) to realize chain operation (2), specify multiple callback functions for the same operation (3), specify callback functions for multiple operations (4), callback function interface for common operations

$.fn. Extend $.fn. Extend $.fn.

$.extend = $.extend = $.extend = $.extend = $.extend = $.extend = $.extend Extend = $.fn. Extend = $.fn. Fn = $.fn. The.fn. Extend method is used to extend the jQuery instance object, which is the jQuery object we get from the page. Fn extends the jQuery prototype. All jQuery instance objects can get the extension method. Others can also be modified with the jQuery

3. What is Chaining?

In almost all type-based languages, if you call a method and return an object as a method parameter, you get chaining. Chaining is the process of linking multiple operations (lines of code) together into a single line of code with a dot “.” Chained code usually requires an operation to have a return value, but for many operations that are void and return nothing, it’s hard to chain. There are solutions, though, that may not be very elegant. The new idea of chained programming has gained popularity in jQuery

Example:

return $.each(this,function(index, obj) {   
    $("<span/>").html("+").css("cursor"."pointer").click(function() {    
        $(obj).width($(obj).width()+ length);   
    }).insertAfter(obj);  
});Copy the code

In the example above, when the $. Each loop completes and returns this object, it still returns a jQuery object, so you can continue your jQuery programming.

$("button").SuperPlus(10).height(26).width(100).css("color"."blue");Copy the code

4. Window. load and Document Ready.

Window.load is an event that executes when the entire document structure and resources are loaded

Documen Ready is when the entire document structure is loaded and executed

5. What does the $sign in Jquery do?

The $sign is just an alias for “jQuery”. It is the jQuery selector.

   // aaa(a);        
$(document).ready(function(){
    /.../
});Copy the code

You can also replace $with jQuery as follows:

jQuery(document).ready(function(){  
    /.../ 
});Copy the code

$(” #main “) is used to select the DOM element with the id of main.

6. What types of selectors are available in Jquery?

From my point of view, there are three types of selectors, as follows:

1. Basic selector: Returns a matching DOM element based on the ID, CSS class name, and element name.

2. Hierarchical selector: Also known as a path selector, you can select the appropriate DOM elements according to the path hierarchy.

3. Filter selector: Filter related conditions based on the previous ones to get the matching DOM elements.

How to use jQuery to set the borders of all elements on the page to 2px wide dashed lines?

The code is as follows:

<script language="javascript" type="text/javascript">        
    $("*").css("border"."2px dotted red"); 
</script>Copy the code