Do you know the wonderful knowledge in Javascript?

  • 2021-10-25 05:45:27
  • OfStack

Battlefield-hardened predecessors have written countless codes and stepped on countless pits. However, some pits may not be touched in one lifetime, because they will not happen in the business code at all ~ ~

1

Function. prototype is actually a function type. The prototype of custom function is object type.


typeof Function.prototype === 'function'; // true

function People() {}
typeof People.prototype === 'object';   // true

So we can set an empty function to do this:


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};

2

Is it true that a variable is not equal to itself?


const x = NaN;
x !== x // true

This is the only one in js language that is not equal to its own data. Why? Because NaN represents a range, not a specific value.
In the earlier isNaN () function, true was returned even if a string was passed in, which was fixed in es 6.


isNaN('abc');    // true
Number.isNaN('abc') // false

So if you want to be compatible with older browsers, use x! = = x to judge whether it is NaN, is a good scheme.

3

Constructor if return has new data


//  Do not return 
function People() {}
const people = new People();  // People {}

//  Returns a number 
function People() {
 return 1;
}
const people = new People();  // People {}

//  Returns a new object 
function Animal() {
 return {
  hello: 'world',
 };
}
const animal = new Animal(); // { hello: 'world' }

Returning a non-object type does not take effect when the constructor is instantiated

4

. call. call is crazy about who is call?


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

function fn2() {
 console.log(2);
}

fn1.call.call(fn2); // 2

So fn1.call. call (fn2) is equivalent to fn2.call (undefined). And no matter how many. call you add, the effect is the same.

5

Can the object after the instance be instantiated again?


function People() {}

const lili = new People();      // People {}
const lucy = new lili.constructor();  // People {}

Because the prototype chain of lili points to the prototype of People, by looking up for features, the constructor, People itself, is finally found on Peopel. prototype

6

What's weird about setTimeout nesting?


console.log(0, Date.now());

setTimeout(() => {
 console.log(1, Date.now());
 setTimeout(() => {
  console.log(2, Date.now());
  setTimeout(() => {
   console.log(3, Date.now());
   setTimeout(() => {
    console.log(4, Date.now());
    setTimeout(() => {
     console.log(5, Date.now());
     setTimeout(() => {
      console.log(6, Date.now());
     });
    });
   });
  });
 });
});

The interval of setTimeout is 1ms in layers 0-4, and at least 4ms in layers 5.

7

The es6 function generates declaration scope when it takes default parameters


var x = 10;

function fn(x = 2, y = function () { return x + 1 }) {
 var x = 5;
 return y();
}

fn();  // 3

8

Function names in function expressions (not function declarations) cannot be overridden


const c = function CC() {
 CC = 123;
 return CC;
};

c(); // Function

Of course, if you set var CC = 123, you can override it by adding declaration keywords.

9

In strict mode, the function's this is undefined instead of Window


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};
0

For modular code packaged by webpack, it is basically strict mode code.

10

The rounding operation can also use bitwise operation


var x = 1.23 | 0; // 1

Because bitwise operations only support 32-bit integers, all decimal points are discarded

11

indexOf () does not need to compare numbers


const arr = [1, 2, 3];

//  Existence, equivalent to  > -1
if ( ~ arr.indexOf(1)) {

}

//  Does not exist, equivalent to  === -1
!~arr.indexOf(1);

Bitwise operation efficiency is high, and the code is simple. You can also use includes () of es6. But write open source library need to consider compatibility of friends or better with indexOf

12

Can getter/setter also be set dynamically?


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};
3

13


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};
4

Floating-point operation is inaccurate and cliche, but errors are acceptable


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};
5

14

How did class grammar sugar inherit?


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};
6

Prototype inheritance of formal code does not directly instantiate the parent class, but instantiates an empty function to avoid repeated declaration of dynamic attributes


const extends = (Child, Super) => {
 const fn = function () {};
 
 fn.prototype = Super.prototype;
 Child.prototype = new fn();
 Child.prototype.constructor = Child;
};

15

es6 can actually deconstruct objects repeatedly


const obj = {
 a: {
  b: 1
 },
 c: 2
};

const { a: { b }, a } = obj;

One line of code gets both a and a. b.
When a and b are used many times, the logic of ordinary people is to deconstruct a first, and then deconstruct b in the next line.

16

Judging whether the code is compressed is actually so beautiful


// OK 
const noop = Function.prototype;
// OK
const noop = () => {};
9

17

Object = = = compares memory addresses, and > = The converted values will be compared


{} === {} // false

//  Implicit conversion  toString()
{} >= {} // true

18

intanceof is judged by whether the prototype is on the prototype chain of the current object


function People() {}
function Man() {}
Man.prototype = new People();
Man.prototype.constructor = Man;

const man = new Man();
man instanceof People;  // true

//  Replace People Prototype of 
People.prototype = {};
man instanceof People;  // false

If you use class of es6, the prototype prototype is not allowed to be redefined, so the above situation will not occur

19


Object.prototype.__proto__ === null; // true

This is the top level of the prototype chain looking up, 1 null

20

parseInt Too small a number produces bug


parseInt(0.00000000454); // 4
parseInt(10.23);     // 10

21


1 + null     // 1
1 + undefined   // NaN

Number(null)   // 0
Number(undefined) // NaN

22

The argument arguments and the shape are synchronized


function test(a, b, c) {
 console.log(a, b, c); // 2, 3, undefined
 
 arguments[0] = 100;
 arguments[1] = 200;
 arguments[2] = 300;
 
 console.log(a, b, c); // 100, 200, undefined
}
test(2, 3);

If the number of arguments passed is insufficient, the synchronization relationship will also fail.
You can also avoid this 1 behavior with use strict Strict Mode, so that arguments is just a copy.

23

void is a stubborn old man


void 0 === undefined     // true
void 1 === undefined     // true
void {} === undefined     // true
void 'hello' === undefined  // true
void void 0 === undefined   // true

I don't have any relatives with anyone ~ ~

24

try/catch/finally also has a specific execution sequence


function fn1() {
 console.log('fn1');
 return 1;
}

function fn2() {
 console.log('fn2');
 return 2;
}

function getData() {
 try {
  throw new Error('');
 } catch (e) {
  return fn1();
 } finally {
  return fn2();
 }
}

console.log(getData());

//  Print sequence : 'fn1', 'fn2', 2

In the try/catch code block, if return xxyyzz; Keyword, then xxyyzz executes and puts the value in a temporary variable, then executes the contents of the finally code block and returns the temporary variable.
If return aabbcc also exists in finally, the new data aabbcc is returned immediately.

25

Is there such a variable x that it is equal to multiple numbers?


const x = {
 value: 0,
 toString() {
  return ++this.value;
 }
}

x == 1 && x == 2 && x == 3;  // true

Through implicit conversion, this is not a difficult thing.

26

Can clearTimeout and clearInterval be used interchangeably


var timeout = setTimeout(() => console.log(1), 1000);
var interval = setInterval(() => console.log(2), 800);

clearInterval(timeout);
clearTimeout(interval);

The answer is: YES. Most browsers support mutual cleanup timers, but it is recommended to use the corresponding cleanup function.

27

What is the printing order below?


setTimeout(() => {
 console.log(1);
}, 0);

new Promise((resolve) => {
 console.log(2);
 resolve();
}).then(() => console.log(3));

function callMe() {
 console.log(4);
}

(async () => {
 await callMe();
 console.log(5);
})();

The answer is: 2, 4, 3, 5, 1

Main Tasks: 2, 4
Micro Tasks: 3, 5
Macro task: 1

28

null is a type of object, but it is not inherited from Object. It is more like an bug left over from history. Since too many people are using this feature, fixing it will lead to thousands of program errors.


typeof null === 'object';       // true
Object.prototype.toString.call(null); // [object Null]
null instanceof Object;        // false

29

Primitive types (except null and undefined) when operating, the engine will automatically wrap the data into objects, and destroy the objects when the operation is finished.


'abc'.substr(1);
(123).toFixed(2);

So any data added to it will be destroyed unless the prototype chain is modified


const data = 'abc';
data.x = 'y';
console.log(data.x); // undefined

data.__proto__.x = 'z';
console.log(data.x); // 'z'

30

If the data exceeds the safe value, it becomes unsafe


Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2; // true

//  Equivalent to 
2 ** 53 === 2 ** 53 + 1;   // true

31

When the function parameter has a default value, it will change 1 cognition


function test(a, b = 1) {
 //  Alias synchronization, non-strict mode is expected to synchronize 
 arguments[0] = 20;
 console.log(a);      // 2
}
//  The number of formal parameters of the detection function, and the expected value is: 2
console.log(test.length);  // 1

test(123);

32

Numbers are all floating-point types. Bit operation, js first converts the number to int type. Compared with other languages, this is an extra performance overhead.


1 | 0      // 1
1.234 | 0    // 1
1.234 | 0.6   // 1

1 & 1      // 1
1.23 & 1.456  // 1

~1       // -2
~1.234     // -2

33

location can jump directly when assigned to location


location = 'http://baidu.com';

34

Do you know another usage of new?


function Test() {
 console.log(new.target === Test); // true
}

new Test();

If a subclass is instantiated, then new. target is not Test, and the effect of abstract class can be achieved by this method

35

There is a difference between + 0 and-0


1/+0 === Infinity
1/-0 === -Infinity

These are the wonderful knowledge in Javascript, do you know? For more information about JavaScript, please pay attention to other related articles on this site!


Related articles: