Summary of JS interview questions

Keywords: Javascript Front-end ECMAScript Interview

Previous points here: ↓
Summary of JS interview questions (I)
Summary of JS interview questions (II)
Summary of JS interview questions (III)
Summary of JS interview questions (IV)
Summary of JS interview questions (V)
Summary of JS interview questions (6)
Summary of JS interview questions (VII)
71. What is the compatibility between IE and standards

Reference answer:

var ev = ev || window.event;
document.documentElement.clientWidth || document.body.clientWidth;
var target = ev.srcElement || ev.target;

72. Variable promotion

Reference answer:

Variable promotion

A. js code execution process

  • 1 variable lifting
  • 2 the code is executed from top to bottom

Variables declared by var keyword and function keyword will be promoted

B. Variable promotion occurs in the current scope of the code.

  • Variable promotion
  • 1. The variable promotion with VaR keyword will declare the variable in advance, but will not assign value in advance.
  • 2 function keyword to promote variables, which will not only declare variables in advance, but also assign variables in advance, that is, promote the whole function body to the top of the code
  • 3. Some codes will not be executed, but variable promotion will still occur. The rules apply to 1 and 2
    1. 1. The code after return will still have variable promotion. The rule applies to 1 and 2
    1. 2. After the code reports an error, the code will still have variable promotion. The rule is applicable to 1 and 2
    1. 3. The code after the break will still have variable promotion. The rule is applicable to 1 and 2
  • 4 some code will not be executed, but variable promotion will still occur, but the rules will change
    1. 1 if judgment statement the variables declared by var keyword and function keyword in the if judgment statement will only be declared in advance and will not be assigned in advance, that is, the function body will not be promoted to the top of the current scope as a whole. Rules 1 and 2 do not apply
    1. 2. The switch case rule is not applicable to 1 and 2
    1. 3. The do while rule is not applicable to 1 and 2
    1. 4. The variables declared in try catch will only be declared in advance and will not be assigned in advance.
  • Ps: variables declared in conditional judgment statements and try catch will only occur in advance regardless of whether they can be executed or not
  • Declaration that no advance assignment will occur.

Resolution:

// If a variable is declared but not assigned, outputting the variable will output undefined
var num;
console.log(num);

// If a variable is not declared or assigned, an error will be reported:
console.log(num); // Output a variable that does not exist Uncaught ReferenceError: num is not defined
// Variable promotion with var keyword
console.log(num);
var num = 123;
console.log(num);
var num = 456;
console.log(num);

// Code after variable promotion:
var num;
console.log(num);
num = 123;
console.log(num);
num = 456;
console.log(num);
// Variable promotion of function keyword
console.log(fn);

function fn() {
    console.log(1);
}

// Code after variable promotion:
function fn() {
    console.log(1);
}
console.log(fn); // Function body of output fn
// 3.1 the code after return will still have variable promotion. The rules are applicable to 1 and 2
function fn() {
    console.log(num);
    return;
    var num = 123;
}
fn();

// Code after variable promotion:
function fn() {
    var num;
    console.log(num);
    return;
    num = 123;
}
fn(); // undefined

function fn() {
    console.log(fo);
    return;

    function fo() {}
}
fn();

// Code after variable promotion:
function fn() {
    function fo() {}
    console.log(fo);
    return;
}
fn(); //Function body of output fo
//3.2 after an error is reported, the code will still carry out variable promotion. The rules are applicable to 1 and 2
console.log(num);
xsasfgdsfqdfsdf; //Report an error
var num = 123;
console.log(num);

// Code after variable promotion:
var num;
console.log(num); //Output undefined
dsagdsqghdwfh; // An error is reported, and the code after the error will not be executed
num = 123;
console.log(num);
//function keyword
console.log(fn);
sasgfdhwhsdqg;

function fn() {}
console.log(fn);

// Code after variable promotion:
function fn() {}
console.log(fn); // Function body of output fn
asdgsdgdfgfdg; // An error is reported, and the code after the error is reported will not be executed
console.log(fn);
//4 the code is not executed, but the variable will be promoted, but the rule does not apply to 1,2
//4.1 if judgment statement
console.log(num);
if (false) {
    var num = 123;
}
console.log(num)

//  Code after variable promotion:
var num;
console.log(num); //undefined
if (false) {
    num = 123;
}
console.log(num) //undefined

console.log(fn);
if (false) {
    function fn() {}
}
console.log(fn);

// Code after variable promotion:
var fn;

function fn;
console.log(fn) //undefined
if (false) {
    function fn() {}
}
console.log(fn) //undefined
/*function fn//Uncaught SyntaxError: Unexpected end of input*/
// try catch
try {
    console.log(num);
} catch (e) {
    var num = 123;
}
console.log(num);

var num;
try {
    console.log(num); // undefined
} catch (e) {
    num = 123;
}
console.log(num); // undefined

try {
    console.log(fn);
} catch (e) {
    function fn() {}
}
console.log(fn);

var fn;
try {
    console.log(fn); // undefined
} catch (e) {
    num = 123;
}
console.log(fn); // undefined

73. How to prevent bubbling and default behavior

Reference answer:

  • Prevent bubbling behavior: non IE browser stopPropagation(), IE browser window. event. cancelBubble = true
  • Block default behavior: non IE browser preventDefault(), IE browser window. event. returnValue = false

Resolution:

When you need to stop bubbling, you can use

function stopBubble(e) {
    //If an event object is provided, then this is a non IE browser
    if (e && e.stopPropagation)
        //Therefore, it supports W3C's stopPropagation() method
        e.stopPropagation();
    //Otherwise, we need to use IE to cancel event bubbling
    else window.event.cancelBubble = true;
}

When you need to block the default behavior, you can use

//Block browser default behavior
function stopDefault(e) {
    //Block default browser actions (W3C)
    if (e && e.preventDefault) e.preventDefault();
    //How to prevent the default action of the function manager in IE
    else window.event.returnValue = false;
    return false;
}

74. Scope of this closure in JS

Reference answer:

this: points to the call context

Closure: defining a function opens up a local scope, and the entire js execution environment has a global scope

Scope: a function can access variables in other functions (closure is a protected variable space)

var f = (function fn() {
        var name = 1;
        return function() {
            name++;
            console.log(name)
        }
    })()

    ==
    >
    undefined In doubt

75. Local objects, built-in objects and host objects of JavaScript

Reference answer:

1. Local objects

ECMA-262 defines a native object as "an Object provided by an ECMAScript implementation independent of the host environment". In short, a native object is a class (reference type) defined by ECMA-262 They include: Object, Function, Array, String, Boolean, Number, Date, RegExp, Error, EvalError, RangeError, ReferenceError, syntax Error, TypeError, URIError

2. Built in objects

There are 17 built-in objects in JS, including Array object, Date object, regular expression object, string object and Global object

3. Host object

The object provided by the host environment implemented by ECMAScript can be understood as the object provided by the browser. All BOM s and DOM are host objects.

76. Homology strategy of JavaScript

Reference answer:

A script can only read the properties of windows and documents from the same source

Resolution:

Homology policy: restricts how documents or scripts loaded from one source interact with resources from another source. This is a key security mechanism for isolating potentially malicious files. (official explanation from MDN)

Simply put, a script can only read the properties of windows and documents from the same source. The same source here refers to the combination of host name, protocol and port number
Specific explanation:

(1) The source includes three parts: protocol, domain name and port (the default port of http protocol is 80). If any part is different, the source is different, that is, cross domain.

(2) Restriction: the document of this source has no right to operate the document of another source. This restriction is reflected in: (remember)

Cookie s, LocalStorage and IndexDB cannot be obtained.

Unable to get and manipulate DOM.

You can't send Ajax requests. Note that AJAX is only suitable for homologous communication.

Trouble caused by the same origin policy: ajax requests under different domain names cannot be realized, and cross domain operations are required

77. Event bubbling and event capture

Reference answer:

Event bubbling: propagates from the most specific element (target element) to the least specific element

Event capture: from the most uncertain element to the target element

78. Foo = foo|bar, what does this line of code mean? Why is it written like this?

Reference answer:

This is called short circuit expression

Resolution:

amount to

var foo;
if (foo) {
    foo = foo;
} else {
    foo = bar;
}

It is often used for null judgment of function parameters

79. How complex data types are converted to strings

Reference answer:

  • First, the valueOf method will be called. If the return value of the method is a basic data type, this value will be returned
  • If the return value after calling the valueOf method is still a complex data type, the toString method of the object will be called
  • If the return value after the toString method call is a basic data type, this value will be returned,
  • If the return value after the toString method call is a complex data type, an error will be reported.

80. The pointing of this in JavaScript

Reference answer:

  • The global environment and ordinary functions (non strict mode) point to window
  • The normal function (strict mode) points to undefined
  • Function as object method and prototype chain points to the object of the upper level
  • Constructor points to the constructed object
  • The element in the DOM event that points to the trigger event
  • Arrow function

Resolution:

1. Global environment

In the global environment, this always points to the global object (window), regardless of strict mode;

// In the browser, the global object is window object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37

2. Function context call

2.1 ordinary function

this in ordinary functions can be divided into two cases, strict mode and non strict mode.

(1) In the non strict mode, it is not called by the upper level object, and this points to the global object window by default.

function f1() {
    return this;
}
f1() === window; // true

(2) In strict mode, this points to undefined.

function f2() {
    "use strict"; // Here is the strict mode
    return this;
}
f2() === undefined; // true

2.2 method of using function as object

(1) If the function is called by the object of the previous level, this refers to the object of the previous level.

(2) For multi-layer nested objects, this of the internal method points to the object closest to the called function (window is also an object, and this of the internal object calling method points to the internal object, not window).

//Mode 1
var o = {
    prop: 37,
    f: function() {
        return this.prop;
    }
};
//When o.f() is called, this in the function is bound to the O object.
console.log(o.f()); // logs 37

//Mode 2
var o = {
    prop: 37
};

function independent() {
    return this.prop;
}
//Function f is called as a member method of o
o.f = independent;
console.log(o.f()); // logs 37

//Mode 3
//The binding of this is only affected by the nearest member reference
o.b = {
    g: independent,
    prop: 42
};
console.log(o.b.g()); // 42

Special examples

// Example 1
var o = {
    a: 10,
    b: {
        // a:12,
        fn: function() {
            console.log(this.a); //undefined
            console.log(this); //{fn: ƒ}
        }
    }
};
o.b.fn();
// Example 2
var o = {
    a: 10,
    b: {
        a: 12,
        fn: function() {
            console.log(this.a); //undefined
            console.log(this); //window
        }
    }
};
var j = o.b.fn;
j();
// this always points to the object that calls it at last, that is, when it executes, who calls it? In example 2, although the function fn is referenced by object b, it does not execute when assigning FN to variable j, so it finally points to window, which is different from example 1, and example 1 directly executes FN.

2.3 this in prototype chain

(1) If the method exists in the prototype chain of an object, this refers to the object that calls the method, just as the method is on the object.

var o = {
    f: function() {
        return this.a + this.b;
    }
};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

In the above example, object p does not have its own f attribute, and its f attribute inherits from its prototype. When p. f() is executed, the prototype chain of p will be found, the F function will be found and executed. Because f is called as a method of p, this in the function points to p.

(2) The same concept applies when a function is called in a getter or setter. Functions used as getters or setters bind this to the object that sets or gets the property.

(3) call() and apply() methods: when a Function is called through the call() and apply() methods inherited from the prototype of the Function object, the internal this value of the Function can be bound to the first object specified by the call() & apply() method. If the first parameter is not an object, JavaScript will try to convert it into an object and point to it.

function add(c, d) {
    return this.a + this.b + c + d;
}
var o = {
    a: 1,
    b: 3
};

add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

function tt() {
    console.log(this);
}
// The first parameter is not an object, and JavaScript will try to convert it into an object and point to it.
tt.call(5); // Internal conversion to Number {[[PrimitiveValue]]: 5}
tt.call("asd"); // Internal conversion to String {0: "a", 1: "s", 2: "d", length: 3, [[PrimitiveValue]]: "asd"}

(4) bind() method: introduced by ES5, on the prototype chain of Function, Function. prototype. bind. After binding through the bind method, the Function will always be bound to its first parameter object, regardless of when it is called.

function f() {
    return this.a;
}

var g = f.bind({
    a: "azerty"
});
console.log(g()); // azerty

var o = {
    a: 37,
    f: f,
    g: g
};
console.log(o.f(), o.g()); // 37, azerty

2.4 this in constructor

When a function is used as a constructor (using the new keyword), its this is bound to the new object being constructed.

The default value returned by the constructor is the object referred to by this, or other objects can be returned manually.

function C() {
    this.a = 37;
}

var o = new C();
console.log(o.a); // 37
// Why does this point to o? First, the new keyword will create an empty object, and then automatically call a function apply method to point this to the empty object. In this way, this inside the function will be replaced by the empty object.

function C2() {
    this.a = 37;
    return {
        a: 38
    }; // Manually set the return {a:38} object
}

o = new C2();
console.log(o.a); // 38

Special examples

When this encounters a return

// Example 1
function fn() {
    this.user = "Dream chaser";
    return {};
}
var a = new fn();
console.log(a.user); //undefined
// Example 2
function fn() {
    this.user = "Dream chaser";
    return function() {};
}
var a = new fn();
console.log(a.user); //undefined
// Example 3
function fn() {
    this.user = "Dream chaser";
    return 1;
}
var a = new fn();
console.log(a.user); //Dream chaser
// Example 4
function fn() {
    this.user = "Dream chaser";
    return undefined;
}
var a = new fn();
console.log(a.user); //Dream chaser
// Example 5
function fn() {
    this.user = "Dream chaser";
    return undefined;
}
var a = new fn();
console.log(a); //fn {user: "dream chaser"}
// Example 6
// Although null is also an object, here this still points to the instance of that function, because null is special
function fn() {
    this.user = "Dream chaser";
    return null;
}
var a = new fn();
console.log(a.user); //Dream chaser

// Summary: if the return value is an object, this refers to the returned object. If the return value is not an object, this still points to the instance of the function.

2. 5 setTimeout & setInterval

(1) For the callback function inside the delay function, this of the function points to the global object window;

(2) You can change the internal function this point through the bind() method.

//Code by default
function Person() {
    this.age = 0;
    setTimeout(function() {
        console.log(this);
    }, 3000);
}

var p = new Person(); //Return the window object after 3 seconds
//Bind by bind
function Person() {
    this.age = 0;
    setTimeout(
        function() {
            console.log(this);
        }.bind(this),
        3000
    );
}

var p = new Person(); //After 3 seconds, return the newly generated object Person {...}

3. In DOM events

3.1 as a DOM event handler

When a function is used as an event handler, its this points to the element that triggers the event (for the addEventListener event).

// When called, turns the associated element blue
function bluify(e) {
    //this points to the clicked element
    console.log("this === e.currentTarget", this === e.currentTarget); // Always true
    // true when currentTarget and target are the same object
    console.log("this === e.target", this === e.target);
    this.style.backgroundColor = "#A5D9F3";
}

// Gets a list of all elements in the document
var elements = document.getElementsByTagName("*");

// Take bluefy as the click listening function of the element. When the element is clicked, it will turn blue
for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener("click", bluify, false);
}

3.2 as an inline event handler

(1) When the code is called by the inline handler function, its this points to the DOM element where the listener is located;

(2) When the code is executed inside a function, its this point is equivalent to the direct call of an ordinary function, that is, it points to the global object window in the non strict mode and undefined in the strict mode:

<button onclick="console.log(this)">show me</button>
<button onclick="(function () {console.log(this)})()">show inner this</button>
<button onclick="(function () {'use strict'; console.log(this)})()">
    use strict
</button>
// Console printing
<button onclick="console.log(this)">show me</button>
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, ...}
undefined

4. Arrow function

4.1 in the global environment

In the global code, the arrow function is set as a global object:

var globalObject = this;
var foo = () => this;
console.log(foo() === globalObject); // true

4.2 this capture context

The arrow function does not have its own this, but uses this of the scope where the arrow function is located, that is, it points to the scope where the arrow function is defined (not at runtime).

//1. The arrow function is inside the function and is used in a non method way
function Person() {
    this.age = 0;
    setInterval(() => {
        this.age++;
    }, 3000);
}
var p = new Person(); //Person{age: 0}

//Ordinary functions as internal functions
function Person() {
    this.age = 0;
    setInterval(function() {
        console.log(this);
        this.age++;
    }, 3000);
}
var p = new Person(); //Window{...}

4.2 this capture context

The arrow function does not have its own this, but uses this of the scope where the arrow function is located, that is, it points to the scope where the arrow function is defined (not at runtime).

//1. The arrow function is inside the function and is used in a non method way
function Person() {
    this.age = 0;
    setInterval(() => {
        console.log(this);
        this.age++;
    }, 3000);
}
var p = new Person(); //Person{age: 0}

//Ordinary functions as internal functions
function Person() {
    this.age = 0;
    setInterval(function() {
        console.log(this);
        this.age++;
    }, 3000);
}
var p = new Person(); //Window{...}

this in setTimeout points to the object newly generated by the constructor, while the ordinary function points to the global window object.

4.3 use arrow function as object method

The arrow function is used as the method of the object, pointing to the global window object; If a normal function is used as a method of an object, it points to the called object.

var obj = {
    i: 10,
    b: () => console.log(this.i, this),
    c: function() {
        console.log(this.i, this);
    }
};
obj.b(); // undefined window{...}
obj.c(); // 10 Object {...}

4. In the arrow function, the call(), apply(), bind() methods are invalid

var adder = {
    base: 1,
    //The arrow function is defined inside the method of the object. this is the scope of the arrow function,
    //This of the method add points to the adder object, so this of the arrow function also points to the adder object.
    add: function(a) {
        var f = v => v + this.base;
        return f(a);
    },
    //this of ordinary function f1 points to window
    add1: function() {
        var f1 = function() {
            console.log(this);
        };
        return f1();
    },
    addThruCall: function inFun(a) {
        var f = v => v + this.base;
        var b = {
            base: 2
        };

        return f.call(b, a);
    }
};

console.log(adder.add(1)); // Output 2
adder.add1(); //Output global object window {...}
console.log(adder.addThruCall(1)); // It still outputs 2 (instead of 3). Its internal this has not changed due to call(). Its this value is still the this value of the function inFun, pointing to the object adder

4.5 this pointing immobilization

The arrow function can make this point fixed, which is very helpful to encapsulate the callback function

var handler = {
    id: "123456",

    init: function() {
        document.addEventListener(
            "click",
            event => this.doSomething(event.type),
            false
        );
    },

    doSomething: function(type) {
        console.log("Handling " + type + " for " + this.id);
    }
};

In the init method of the above code, the arrow function is used, which causes this in the arrow function to always point to the handler object. If the arrow function is not used, it will point to the global document object.

4.6 arrow letter is not applicable

(1) The arrow function is not suitable for defining the method of the object (there is this in the method), because it points to window at this time;

(2) Arrow functions should not be used when dynamic this is required.

//Example 1: this points to the scope where the arrow function is defined. It is located in the object cat, but cat cannot form a scope, so it points to the global window. After changing to an ordinary function, this points to the cat object.
const cat = {
    lives: 9,
    jumps: () => {
        this.lives--;
    }
};

//Example 2: at this time, this also points to the window and cannot dynamically listen to the button. After changing to an ordinary function, this points to the button object.
var button = document.getElementById("press");
button.addEventListener("click", () => {
    this.classList.toggle("on");
});

Posted by sadaf on Sat, 27 Nov 2021 23:55:37 -0800