JavaScript奇葩知识大全

开发 前端
久经沙场的前辈们,写了无数代码,踩了无数的坑。但有些坑,可能一辈子也踩不到摸不着,因为根本不会发生在业务代码里。

[[350390]]

 久经沙场的前辈们,写了无数代码,踩了无数的坑。但有些坑,可能一辈子也踩不到摸不着,因为根本不会发生在业务代码里~~

1. 

Function.prototype 竟然是个函数类型。而自定义函数的原型却是对象类型。 

  1. typeof Function.prototype === 'function';  // true  
  2. function People() {}  
  3. typeof People.prototype === 'object';      // true 

所以我们设置空函数可以这么做: 

  1. // Good   
  2. const noop = Function.prototype;  
  3. // Bad  
  4. const noop = () => {}; 

2. 

一个变量真的会不等于自身吗? 

  1. const x = NaN 
  2. x !== x  // true 

这是目前为止 js 语言中唯一的一个不等于自己的数据。为什么?因为 NaN 代表的是一个范围,而不是一个具体的数值。在早期的 isNaN() 函数中,即使传入字符串,也会返回 true ,这个问题已经在 es6 中修复。 

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

所以如果您想兼容旧浏览器,用 x !== x 来判断是不是NaN,是一个不错的方案。

3. 

构造函数如果 return了新的数据 

  1. // 不返回  
  2. function People() {}  
  3. const people = new People();   // People {}  
  4. // 返回数字  
  5. function People() {  
  6.   return 1;  
  7.  
  8. const people = new People();   // People {}  
  9. // 返回新对象  
  10. function Animal() {  
  11.   return {  
  12.     hello: 'world',  
  13.   };  
  14.  
  15. const animal = new Animal();  // { hello: 'world' } 

在实例化构造函数时,返回非对象类型将不生效

4. 

call.call 到底在为谁疯狂打call? 

  1. function fn1() {  
  2.   console.log(1);  
  3.  
  4. function fn2() {  
  5.   console.log(2);  
  6.  
  7. fn1.call.call(fn2); // 2 

所以 fn1.call.call(fn2) 等效于 fn2.call(undefined)。而且无论您加多少个 .call,效果也是一样的。

5. 

实例后的对象也能再次实例吗? 

  1. function People() {}  
  2. const lili = new People();            // People {}  
  3. const lucy = new tom.constructor();   // People {} 

因为 lili 的原型链指向了 People 的原型,所以通过向上寻找特性,最终在 Peopel.prototype 上找到了构造器即 People 自身

6. 

setTimeout 嵌套会发生什么奇怪的事情? 

  1. console.log(0, Date.now());  
  2. setTimeout(() => {  
  3.   console.log(1, Date.now());  
  4.   setTimeout(() => {  
  5.     console.log(2, Date.now());  
  6.     setTimeout(() => {  
  7.       console.log(3, Date.now());  
  8.       setTimeout(() => {  
  9.         console.log(4, Date.now());  
  10.         setTimeout(() => {  
  11.           console.log(5, Date.now());  
  12.           setTimeout(() => {  
  13.             console.log(6, Date.now());  
  14.           });  
  15.         });  
  16.       });  
  17.     });  
  18.   });  
  19. }); 

在0-4层,setTimeout 的间隔是 1ms ,而到第 5 层时,间隔至少是 4ms 。

7. 

es6函数带默认参数时将生成声明作用域 

  1. var x = 10 
  2. function fn(x = 2y = function () { return x + 1 }) {  
  3.   var x = 5 
  4.   return y();  
  5. fn();   // 3 

8. 

函数表达式(非函数声明)中的函数名不可覆盖 

  1. const c = function CC() {  
  2.   CC = 123 
  3.   return CC;  
  4. }; 
  5. c(); // Function 

当然,如果设置 var CC = 123 ,加声明关键词是可以覆盖的。

9. 

严格模式下,函数的 this 是 undefined 而不是 Window 

  1. // 非严格  
  2. function fn1() {  
  3.   return this;  
  4.  
  5. fn1(); // Window  
  6. // 严格  
  7. function fn2() {  
  8.   'use strict';  
  9.   return this;  
  10. fn2(); // undefined 

对于模块化的经过webpack打包的代码,基本都是严格模式的代码。

10. 

取整操作也可以用按位操作

  1. var x = 1.23 | 0;  // 1 

因为按位操作只支持32位的整型,所以小数点部分全部都被抛弃

11. 

indexOf() 不需要再比较数字 

  1. const arr = [1, 2, 3];  
  2. // 存在,等效于 > -1  
  3. if (~arr.indexOf(1)) { 
  4.  
  5. // 不存在,等效于 === -1  
  6. !~arr.indexOf(1); 

按位操作效率高点,代码也简洁一些。也可以使用es6的 includes() 。但写开源库需要考虑兼容性的道友还是用 indexOf 比较好

12. 

getter/setter 也可以动态设置吗? 

  1. class Hello {  
  2.   _name = 'lucy' 
  3.   getName() {  
  4.     return this._name;  
  5.   }  
  6.   // 静态的getter 
  7.    get id() {  
  8.     return 1;  
  9.   }  
  10. const hel = new Hello();  
  11. hel.name;       // undefined  
  12. hel.getName();  // lucy  
  13. // 动态的getter  
  14. Hello.prototype.__defineGetter__('name', function() {  
  15.   return this._name;  
  16. });  
  17. Hello.prototype.__defineSetter__('name', function(value) {  
  18.   this._name = value 
  19. });  
  20. hel.name;       // lucy  
  21. hel.getName();  // lucy   
  22. hel.name = 'jimi' 
  23. hel.name;       // jimi  
  24. hel.getName();  // jimi 

13 

  1. 0.3 - 0.2 !== 0.1  // true 

浮点操作不精确,老生常谈了,不过可以接受误差 

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

14. 

class 语法糖到底是怎么继承的? 

  1. function Super() {  
  2.   this.a = 1 
  3.  
  4. function Child() {  
  5.   // 属性继承  
  6.   Super.call(this);  
  7.   this.b = 2 
  8.  
  9. // 原型继承  
  10. Child.prototype = new Super();  
  11. const child = new Child();  
  12. child.a;  // 1 

正式代码的原型继承,不会直接实例父类,而是实例一个空函数,避免重复声明动态属性 

  1. const extends = (Child, Super) => {  
  2.   const fn = function () {};  
  3.   fn.prototype = Super.prototype;  
  4.   Child.prototype = new fn();  
  5.   ChildChild.prototype.constructor = Child;  
  6. }; 

15

es6居然可以重复解构对象 

  1. const obj = {  
  2.   a: {  
  3.     b: 1  
  4.   },  
  5.   c: 2  
  6. };  
  7. const { a: { b }, a } = obj; 

一行代码同时获取 a 和 a.b 。在a和b都要多次用到的情况下,普通人的逻辑就是先解构出 a ,再在下一行解构出 b 。

16

判断代码是否压缩居然也这么秀 

  1. function CustomFn() {}  
  2. const isCrashed = typeof CustomFn.name === 'string' && CustomFn.name === 'CustomFn'; 

17

对象 === 比较的是内存地址,而 >= 将比较转换后的值 

  1. {} === {} // false  
  2. // 隐式转换 toString() 
  3. {} >= {}  // true 

18

intanceof 的判断方式是原型是否在当前对象的原型链上面 

  1. function People() {}  
  2. function Man() {}  
  3. Man.prototype = new People();  
  4. ManMan.prototype.constructor = Man;  
  5. const man = new Man();  
  6. man instanceof People;    // true  
  7. // 替换People的原型  
  8. People.prototype = {};  
  9. man instanceof People;    // false 

如果您用es6的class的话,prototype原型是不允许被重新定义的,所以不会出现上述情况

19

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

这是原型链向上查找的最顶层,一个 null

20

parseInt 太小的数字会产生 bug 

  1. parseInt(0.00000000454);  // 4  
  2. parseInt(10.23);          // 10 

21 

  1. 1 + null          // 1  
  2. 1 + undefined     // NaN  
  3. Number(null)      // 0  
  4. Number(undefined) // NaN 

22

arguments 和形参是别名关系 

  1. function test(a, b) {  
  2.   console.log(a, b); // 2, 3  
  3.   arguments[0] = 100;  
  4.   arguments[1] = 200;  
  5.   console.log(a, b); // 100, 200 
  6.  
  7. test(2, 3); 

但是您可以用 use strict 严格模式来避免这一行为,这样 arguments 就只是个副本了。

23

void 是个固执的老头 

  1. void 0 === undefined          // true  
  2. void 1 === undefined          // true  
  3. void {} === undefined         // true  
  4. void 'hello' === undefined    // true  
  5. void void 0 === undefined     // true 

跟谁都不沾亲~~

24

try/catch/finally 也有特定的执行顺序 

  1. function fn1() {  
  2.   console.log('fn1');  
  3.   return 1;  
  4.  
  5. function fn2() {  
  6.   console.log('fn2');  
  7.   return 2;  
  8.  
  9. function getData() {  
  10.   try {  
  11.     throw new Error('');  
  12.   } catch (e) {  
  13.     return fn1();  
  14.   } finally {  
  15.     return fn2();  
  16.   }  
  17.  
  18. console.log(getData());  
  19. // 打印顺序: 'fn1', 'fn2', 2 

在 try/catch 代码块中,如果碰到 return xxyyzz; 关键词,那么 xxyyzz 会先执行并把值放在临时变量里,接着去执行 finally 代码块的内容后再返回该临时变量。如果 finally 中也有 return aabbcc ,那么会立即返回新的数据 aabbcc 。

25

是否存在这样的变量 x ,使得它等于多个数字? 

  1. const x = {  
  2.   value: 0,  
  3.   toString() {  
  4.     return ++this.value;  
  5.   }  
  6.  
  7. x == 1 && x == 2 && x == 3;    // true 

通过隐式转换,这样不是什么难的事情。

26 

  1. clearTimeout 和 clearInterval 可以互换~~~~使用吗  
  2. var timeout = setTimeout(() => console.log(1), 1000);  
  3. var interval = setInterval(() => console.log(2), 800);  
  4. clearInterval(timeout);  
  5. clearTimeout(interval); 

答案是:YES 。大部分浏览器都支持互相清理定时器,但是建议使用对应的清理函数。

27

下面的打印顺序是? 

  1. setTimeout(() => {  
  2.   console.log(1);  
  3. }, 0);  
  4. new Promise((resolve) => {  
  5.   console.log(2);  
  6.   resolve();  
  7. }).then(() => console.log(3));  
  8. function callMe() {  
  9.   console.log(4);  
  10.  
  11. (async () => {  
  12.   await callMe();  
  13.   console.log(5);  
  14. })(); 

答案是:2, 4, 3, 5, 1

主线任务:2,4

微任务:3,5

宏任务:1

28

null 是 object 类型,但又不是继承于 Object ,它更像一个历史遗留的 bug 。鉴于太多人在用这个特性,修复它反而会导致成千上万的程序出错。 

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

脑袋空了,想到再加。。。 

 

责任编辑:庞桂玉 来源: 前端教程
相关推荐

2020-11-08 14:38:35

JavaScript代码开发

2012-03-19 09:24:25

JavaScript

2020-03-09 14:40:52

JavaScript工具函数前端

2010-07-16 11:22:31

Perl

2019-06-09 08:37:17

2009-10-26 14:00:03

光纤接入网

2010-07-23 13:16:07

Perl

2009-10-19 16:15:11

网络综合布线工程

2015-11-02 11:46:36

bug开发程序员

2009-01-11 09:14:45

Javascript开发总结

2016-10-31 19:22:24

JavaScript语法

2010-05-25 14:05:52

MySQL数据库

2015-07-16 10:15:44

web前端知识体系

2021-07-20 10:26:12

JavaScriptasyncawait

2009-08-24 17:07:09

C# 泛型

2021-12-14 08:51:23

Linux 中断子系统Linux 系统

2017-02-20 23:05:14

JavaScript

2017-12-04 12:29:15

前端JavaScript性能优化

2011-03-31 14:46:29

MySQL数据库备份

2010-01-25 11:55:41

MySQL数据库备份数据库安全
点赞
收藏

51CTO技术栈公众号