JavaScript里的奇葩知识,你遇到过吗?

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

安图网站建设公司创新互联,安图网站设计制作,有大型网站制作公司丰富经验。已为安图成百上千家提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的安图做网站的公司定做!

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 = 2, y = function () { return x + 1 }) {
  3.   var x = 5;
  4.   return y();
  5. }
  6. 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. }
  11. 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.  
  4.   getName() {
  5.     return this._name;
  6.   }
  7.   
  8.   // 静态的getter
  9.   get id() {
  10.     return 1;
  11.   }
  12. }
  13. const hel = new Hello();
  14. hel.name;       // undefined
  15. hel.getName();  // lucy
  16. // 动态的getter
  17. Hello.prototype.__defineGetter__('name', function() {
  18.   return this._name;
  19. });
  20. Hello.prototype.__defineSetter__('name', function(value) {
  21.   this._name = value;
  22. });
  23. hel.name;       // lucy
  24. hel.getName();  // lucy
  25. hel.name = 'jimi';
  26. hel.name;       // jimi
  27. 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.   
  4.   fn.prototype = Super.prototype;
  5.   Child.prototype = new fn();
  6.   ChildChild.prototype.constructor = Child;
  7. };

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.   
  4.   arguments[0] = 100;
  5.   arguments[1] = 200;
  6.   
  7.   console.log(a, b); // 100, 200
  8. }
  9. 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

clearTimeout 和 clearInterval 可以互换~~~~使用吗

 
 
 
  1. var timeout = setTimeout(() => console.log(1), 1000);
  2. var interval = setInterval(() => console.log(2), 800);
  3. clearInterval(timeout);
  4. 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

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

网页名称:JavaScript里的奇葩知识,你遇到过吗?
网页地址:http://www.hantingmc.com/qtweb/news19/515419.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联