1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Javascript 里的奇葩知識,長見識了!

        共 7202字,需瀏覽 15分鐘

         ·

        2021-01-27 09:52

        作者:原罪

        原文:https://segmentfault.com/a/1190000023941089

        久經沙場的前輩們,寫了無數(shù)代碼,踩了無數(shù)的坑。但有些坑,可能一輩子也踩不到摸不著,因為根本不會發(fā)生在業(yè)務代碼里~~

        1

        Function.prototype?竟然是個函數(shù)類型。而自定義函數(shù)的原型卻是對象類型。

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

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

        所以我們設置空函數(shù)可以這么做:

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

        2

        一個變量真的會不等于自身嗎?

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

        這是目前為止js語言中唯一的一個不等于自己的數(shù)據(jù)。為什么?因為NaN代表的是一個范圍,而不是一個具體的數(shù)值。在早期的 isNaN() 函數(shù)中,即使傳入字符串,也會返回true,這個問題已經在es6中修復。

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

        所以如果您想兼容舊瀏覽器,用?x !== x?來判斷是不是NaN,是一個不錯的方案。

        3

        構造函數(shù)如果return了新的數(shù)據(jù)

        // 不返回
        function People() {}
        const people = new People(); // People {}

        // 返回數(shù)字
        function People() {
        return 1;
        }
        const people = new People(); // People {}

        // 返回新對象
        function Animal() {
        return {
        hello: 'world',
        };
        }
        const animal = new Animal(); // { hello: 'world' }

        在實例化構造函數(shù)時,返回非對象類型將不生效

        4

        .call.call?到底在為誰瘋狂打call?

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

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

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

        所以?fn1.call.call(fn2)?等效于?fn2.call(undefined)。而且無論您加多少個?.call,效果也是一樣的。

        5

        實例后的對象也能再次實例嗎?

        function People() {}

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

        因為lili的原型鏈指向了People的原型,所以通過向上尋找特性,最終在?Peopel.prototype?上找到了構造器即 People自身

        6

        setTimeout?嵌套會發(fā)生什么奇怪的事情?

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

        在0-4層,setTimeout的間隔是1ms,而到第5層時,間隔至少是4ms。

        7

        es6函數(shù)帶默認參數(shù)時將生成聲明作用域

        var x = 10;

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

        fn(); // 3

        8

        函數(shù)表達式(非函數(shù)聲明)中的函數(shù)名不可覆蓋

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

        c(); // Function

        當然,如果設置var CC = 123,加聲明關鍵詞是可以覆蓋的。

        9

        嚴格模式下,函數(shù)的this是undefined而不是Window

        // 非嚴格
        function fn1() {
        return this;
        }
        fn1(); // Window

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

        對于模塊化的經過webpack打包的代碼,基本都是嚴格模式的代碼。

        10

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

        var x = 1.23 | 0;  // 1

        因為按位操作只支持32位的整型,所以小數(shù)點部分全部都被拋棄

        11

        indexOf() 不需要再比較數(shù)字

        const arr = [1, 2, 3];

        // 存在,等效于 > -1
        if (~arr.indexOf(1)) {

        }

        // 不存在,等效于 === -1
        !~arr.indexOf(1);

        按位操作效率高點,代碼也簡潔一些。也可以使用es6的includes()。但寫開源庫需要考慮兼容性的道友還是用indexOf比較好

        12

        getter/setter 也可以動態(tài)設置嗎?

        class Hello {
        _name = 'lucy';

        getName() {
        return this._name;
        }

        // 靜態(tài)的getter
        get id() {
        return 1;
        }
        }

        const hel = new Hello();

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

        // 動態(tài)的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

        浮點操作不精確,老生常談了,不過可以接受誤差

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

        14

        class語法糖到底是怎么繼承的?

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

        function Child() {
        // 屬性繼承
        Super.call(this);
        this.b = 2;
        }
        // 原型繼承
        Child.prototype = new Super();

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

        正式代碼的原型繼承,不會直接實例父類,而是實例一個空函數(shù),避免重復聲明動態(tài)屬性

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

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

        15

        es6居然可以重復解構對象

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

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

        一行代碼同時獲取aa.b。在a和b都要多次用到的情況下,普通人的邏輯就是先解構出a,再在下一行解構出b。

        16

        判斷代碼是否壓縮居然也這么秀

        function CustomFn() {}

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

        17

        對象===比較的是內存地址,而>=將比較轉換后的值

        {} === {} // false

        // 隱式轉換 toString()
        {} >= {} // true

        18

        intanceof?的判斷方式是原型是否在當前對象的原型鏈上面

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

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

        // 替換People的原型
        People.prototype = {};
        man instanceof People; // false

        如果您用es6的class的話,prototype原型是不允許被重新定義的,所以不會出現(xiàn)上述情況

        19

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

        這是原型鏈向上查找的最頂層,一個null

        20

        parseInt太小的數(shù)字會產生bug

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

        21

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

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

        22

        實參arguments和形參會保持同步關系

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

        如果實參傳的個數(shù)不足,那么同步關系也會失效。您也可以用use strict嚴格模式來避免這一行為,這樣arguments就只是個副本了。

        23

        void是個固執(zhí)的老頭

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

        跟誰都不沾親~~

        24

        try/catch/finally也有特定的執(zhí)行順序

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

        // 打印順序: 'fn1', 'fn2', 2

        try/catch代碼塊中,如果碰到return xxyyzz;關鍵詞,那么xxyyzz會先執(zhí)行并把值放在臨時變量里,接著去執(zhí)行finally代碼塊的內容后再返回該臨時變量。如果finally中也有return aabbcc,那么會立即返回新的數(shù)據(jù)aabbcc。

        25

        是否存在這樣的變量x,使得它等于多個數(shù)字?

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

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

        通過隱式轉換,這樣不是什么難的事情。

        26

        clearTimeout 和 clearInterval 可以互換使用嗎

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

        clearInterval(timeout);
        clearTimeout(interval);

        答案是:YES。大部分瀏覽器都支持互相清理定時器,但是建議使用對應的清理函數(shù)。

        27

        下面的打印順序是?

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

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

        主線任務:2,4 微任務:3,5 宏任務:1

        28

        null是object類型,但又不是繼承于Object,它更像一個歷史遺留的bug。鑒于太多人在用這個特性,修復它反而會導致成千上萬的程序出錯。

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

        29

        基本類型(null和undefined除外)在操作的時候,引擎會自動為數(shù)據(jù)包裝成對象,操作完就銷毀對象。

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

        所以增加任何數(shù)據(jù)上去都會被銷毀,除非修改原型鏈

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

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

        30

        數(shù)據(jù)超過了安全值就變得不安全了

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

        // 等價于
        2 ** 53 === 2 ** 53 + 1; // true

        31

        函數(shù)形參帶默認值時,會改變一些認知

        function test(a, b = 1) {
        // 別名同步,非嚴格模式預期可以同步
        arguments[0] = 20;
        console.log(a); // 2
        }
        // 檢測函數(shù)的形參個數(shù),預期值為:2
        console.log(test.length); // 1

        test(123);

        32

        數(shù)字都是浮點類型。位運算操作時,js會先把數(shù)字轉換到int類型。相對于其他語言,這算是一筆額外的性能開銷。

        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可以直接跳轉

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

        34

        你知道new的另一個用法嗎?

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

        new Test();

        如果實例了子類,那么new.target就不是Test了,通過這個方法可以實現(xiàn)abstract class的效果

        35

        +0 和 -0 是有區(qū)別的

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




        最近好文:
        1. 你真的懂 JavaScript 閉包與高階函數(shù)嗎?

        2. 這些 JS 中強大的操作符,總有幾個你沒聽說過

        3. 我最近在看什么 -《富爸爸窮爸爸》

        4. Mac 中不可錯過的幾款軟件,相見恨晚?。ɑ久赓M)

        5. Chrome 87 新特性解讀,多年來 Chrome 性能最大提升!

        6. 誰說前端不用懂,手摸手 Docker 從入門到實踐



        最后



        如果你覺得這篇內容對你挺有啟發(fā),我想邀請你幫我三個小忙:

        1. 點個「在看」,讓更多的人也能看到這篇內容(喜歡不點在看,都是耍流氓 -_-)

        2. 歡迎加我微信「qianyu443033099」拉你進技術群,長期交流學習...

        3. 關注公眾號「前端下午茶」,持續(xù)為你推送精選好文,也可以加我為好友,隨時聊騷。


        點個在看支持我吧,轉發(fā)就更好了


        瀏覽 39
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            人人爱人人撸 | 免费黄片视频大全 | 婷婷五月丁香网狠狠色综合 | 免费无码婬片AAAA片老婦 | 成人无码在线免费观看 | 国产全肉乱妇杂乱视频在线观看 | 91搞鸡| 人妻少妇一区二区 | 91色屁屁TS人妖系列二区 | 国产棈品久久久久久久久久九秃 |