[JS] 877 - 35 wonderful knowledge of JavaScript, long experience!

Front end self study course 2021-02-23 00:28:41
js wonderful knowledge javascript long


author : The original sin

original text :https://segmentfault.com/a/1190000023941089

Veteran veterans , Wrote a lot of code , Stepped on countless pits . But there are some holes , Maybe I can't touch it all my life , Because it doesn't happen in business code at all ~~

1

Function.prototype  It turns out to be a function type . The prototype of a custom function is an object type .

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

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

So we can do this by setting up empty functions :

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

2

Is a variable really not equal to itself ?

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

This is so far js The only data in a language that doesn't equal itself . Why? ? because NaN It represents a scope , Not a specific number . Early isNaN() Function , Even if you pass in a string , And will return to true, The problem is already in es6 Medium repair .

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

So if you want to be compatible with old browsers , use  x !== x  It is not to judge NaN, It's a good plan .

3

Constructor if return We've got new data

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

// Return to digital
function People() {
return 1;
}
const people = new People(); // People {}

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

When instantiating the constructor , return The object Type will not take effect

4

.call.call  Who are you fighting for call?

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

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

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

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

5

Can the object after instance be instantiated again ?

function People() {}

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

because lili Of Prototype chain Yes People The prototype of the , So by looking up for features , In the end in  Peopel.prototype  We found the constructor on the People Oneself

6

setTimeout  There's something strange going on ?

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());
});
});
});
});
});
});

stay 0-4 layer ,setTimeout What's the interval 1ms, And by the end of 5 When the layer , The interval is at least 4ms.

7

es6 Function with default arguments generates Declaration scope

var x = 10;

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

fn(); // 3

8

Function expression ( Non function declaration ) The function name in cannot be overridden

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

c(); // Function

Of course , If you set var CC = 123, It can be covered by declaration keywords .

9

In strict mode , Functional this yes undefined instead of Window

// Not strictly 
function fn1() {
return this;
}
fn1(); // Window

// Strictly
function fn2() {
'use strict';
return this;
}
fn2(); // undefined

For the process of modularization webpack Packaged code , It's basically strict pattern code .

10

Rounding can also be done by bit

var x = 1.23 | 0; // 1

Because bitwise operation only supports 32 Bit integers , So all the decimal parts are discarded

11

indexOf() There's no need to compare numbers

const arr = [1, 2, 3];

// There is , Equivalent to > -1
if (~arr.indexOf(1)) {

}

// non-existent , Equivalent to === -1
!~arr.indexOf(1);

High efficiency of bit by bit operation , The code is also simpler . You can also use es6 Of includes(). But Taoyou, who needs to consider compatibility when writing open source libraries, still uses indexOf better

12

getter/setter Can you also set it dynamically ?

class Hello {
_name = 'lucy';

getName() {
return this._name;
}

// Static getter
get id() {
return 1;
}
}

const hel = new Hello();

hel.name; // undefined
hel.getName(); // lucy

// Dynamic getter
Hello.prototype.__defineGetter__('name', function() {
return this._name;
});

Hello.prototype.__defineSetter__('name', function(value) {
this._name = value;
});

hel.name; // lucy
hel.getName(); // lucy

hel.name = 'jimi';
hel.name; // jimi
hel.getName(); // jimi

13

0.3 - 0.2 !== 0.1 // true

Floating point operations are imprecise , It's a cliche , But the error is acceptable

0.3 - 0.2 - 0.1 <= Number.EPSILON // true

14

class How does grammar sugar inherit ?

function Super() {
this.a = 1;
}

function Child() {
// inheritance of attribute
Super.call(this);
this.b = 2;
}
// Prototype inheritance
Child.prototype = new Super();

const child = new Child();
child.a; // 1

Prototype inheritance of formal code , The parent class is not instantiated directly , It's an example of an empty function , Avoid repeatedly declaring dynamic properties

const extends = (Child, Super) => {
const fn = function () {};

fn.prototype = Super.prototype;
Child.prototype = new fn();
Child.prototype.constructor = Child;
};

15

es6 You can deconstruct objects repeatedly

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

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

One line of code gets a and a.b. stay a and b When it's used many times , The logic of ordinary people is to deconstruct a, On the next line, deconstruct b.

16

Judging whether the code is compressed is so beautiful

function CustomFn() {}

const isCrashed = typeof CustomFn.name === 'string' && CustomFn.name === 'CustomFn';

17

object === Compare memory addresses , and >= The converted values will be compared

{} === {} // false

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

18

intanceof  The way to judge is 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 The prototype of the
People.prototype = {};
man instanceof People; // false

If you use es6 Of class Words ,prototype Prototypes are not allowed to be redefined , So that's not going to happen

19

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

This is what the prototype chain looks up At the top , One null

20

parseInt Too small a number will produce bug

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

21

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

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

22

Actual parameters arguments And formal parameters 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 is not enough , Then the synchronization relationship will also fail . You can also use use strict Strict patterns to avoid this behavior , such arguments It's just a copy .

23

void He's 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'm not related to anyone ~~

24

try/catch/finally There is also a specific order of execution

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 order : 'fn1', 'fn2', 2

stay try/catch Block of code , If you come across return xxyyzz; key word , that xxyyzz It will be executed first and put the value in the temporary variable , Then go ahead and execute finally The temporary variable is returned after the contents of the code block . If finally There are also return aabbcc, Then the new data will be returned immediately aabbcc.

25

Is there such a variable x, Make it equal to more than one number ?

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

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

By implicit transformation , It's not that hard .

26

clearTimeout and clearInterval Can it 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

The following print order is ?

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 task :2,4 Micro task :3,5 Macro task :1

28

null yes object type , But it's not inherited from Object, It's more like a legacy of history bug. Since so many people are using this feature , Fixing it can lead to thousands of bugs .

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

29

Basic types (null and undefined With the exception of ) In operation , The engine will automatically wrap the data into objects , Destroy the object after the operation .

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

So any data added will be destroyed , Unless you modify the prototype chain

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 insecure

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

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

31

When a function parameter has a default value , It's going to change some perception

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

test(123);

32

Numbers are floating point types . Bit operation ,js I'll convert the numbers to int type . Compared with other languages , This is an additional 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

Assign a value to location You can jump straight

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

34

You know, new Another use of ?

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

new Test();

If subclasses are instantiated , that new.target It's not Test 了 , In this way, we can realize abstract class The effect of

35

+0 and -0 There is a difference

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


1. JavaScript Revisit the series (22 Complete )
2. ECMAScript Revisit the series (10 Complete )
3. JavaScript Design patterns Revisit the series (9 Complete )
4.  Regular / frame / Algorithm etc. Revisit the series (16 Complete )
5.  Webpack4 introduction ( On ) ||  Webpack4 introduction ( Next )
6.  MobX introduction ( On )  ||   MobX introduction ( Next )
7. 100 + Summary of original series

reply “ Add group ” Communicate and learn with the big guys ~

Click on “ Read the original ” see 100+ Original articles

This article is from WeChat official account. - Front end self study (FE-study).
If there is any infringement , Please contact the support@oschina.cn Delete .
Participation of this paper “OSC Source creation plan ”, You are welcome to join us , share .

版权声明
本文为[Front end self study course]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222163333661T.html

  1. 【微前端】微前端最终章-qiankun指南以及微前端整体探索
  2. Vue-Cli 创建vue3项目
  3. Go in the front of the progress of u boot v7.0 U disk boot disk production tools
  4. 使用NTLM的windows身份验证的nginx反向代理
  5. Rust教程:针对JavaScript开发人员的Rust简介
  6. 使用 Serverless Framework 部署个人博客到腾讯云
  7. #研發解決方案#易車前端監控系統
  8. Vue changes localhost to IP address and cannot access
  9. JavaScript进阶学习
  10. HTML5 from entry to proficient, realize annual salary 10W +, zero basic students must see
  11. Vue:vuex状态数据持久化插件vuex-persistedstate
  12. Vue source code analysis - start
  13. Vue -- the child component calls the method of the parent component and passes parameters --- props
  14. React-Native 获取设备当前网络状态 NetInfo
  15. 高性能 Nginx HTTPS 调优 - 如何为 HTTPS 提速 30%
  16. How to learn HTML5? How can Xiaobai start HTML5 quickly?
  17. HTML + CSS detailed tutorial, this article is enough, but also quickly save
  18. JavaScript高级:JavaScript面向对象,JavaScript内置对象,JavaScript BOM,JavaScript封装
  19. Why Vue uses asynchronous rendering
  20. JavaScript高级:JavaScript面向对象,JavaScript内置对象,JavaScript BOM,JavaScript封装
  21. vue判断elementui中el-form是否更新变化,变化就提示是否保存,没变就直接离开
  22. 算法题:两数之和——JavaScript及Java实现
  23. 高性能 Nginx HTTPS 调优
  24. Why Vue uses asynchronous rendering
  25. day 31 jQuery进阶
  26. day 30 jQuery
  27. CSS whimsy -- using background to create all kinds of wonderful backgrounds
  28. Why are more and more people learning front end?
  29. What do you do with 4K front-end development?
  30. 8 years of front-end development knowledge precipitation (do not know how many words, keep writing it...)
  31. What is the annual salary of a good web front end?
  32. Front end novice tutorial! How to get started with web front end
  33. Will the front end have a future?
  34. Is the front end hard to learn?
  35. Seven new Vue combat skills to improve efficiency in 2021!
  36. Is front end learning difficult?
  37. How about the process of Web front-end development and self-study?
  38. Front end learning route from zero basis to proficient
  39. What is the basis of learning front end?
  40. What knowledge points need to be learned for self-study front end? How long can I become a front-end Engineer?
  41. An inexperienced front-end engineer, what are the common problems when writing CSS?
  42. HttpServletRequest get URL (parameter, path, port number, protocol, etc.) details
  43. Springboot starts http2
  44. Enabling http2.0 in spring boot
  45. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  46. Using JavaScript in Safari browser history.back () the page will not refresh after returning to the previous page
  47. vue.js Error in win10 NPM install
  48. In less than two months, musk made more than $1 billion, more than Tesla's annual profit
  49. Springboot starts http2
  50. Vue event bus
  51. JQuery easy UI tutorial: custom data grid Pagination
  52. Using okhttp and okhttpgo to obtain onenet cloud platform data
  53. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  54. HTTP 1. X learning notes: an authoritative guide to Web Performance
  55. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  56. HTTP 1. X learning notes: an authoritative guide to Web Performance
  57. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  58. Event bubble and capture in JavaScript
  59. The root element is missing solution
  60. Event bubble and capture in JavaScript