2-7、this不同场景,如何取值?

55 阅读1分钟
<script>
    /*
        普通函数中的this
        非严格模式 this -> window
        严格模式下 this -> undefined
    */
    "use strict";
    function a() {
        console.log(this);
    }

    a();
</script>

<script>
    /*
        call apply bind 中的this
        情况1:this -> window
            a.call()
            a.call(undefined)
            a.call(null)
        情况2:传什么,this就是什么
    */
    function a() {
        console.log(this);
    }

    a.call(123);
    // a.call(undefined);
    // a.call(null);

    // a.apply("abc");
    // a.apply(undefined);
    // a.apply(null);

    const fn = a.bind({ x: 101 })
    fn();
</script>

<script>
    /*
        定时器中的this
        情况1:定时器+function   this->window
        情况2:定时器+箭头函数   this->上层作用域的this
    */

    // 情况1
    // setTimeout(function () {
    //     console.log(this);
    // }, 100)

    // function fn() {
    //     setTimeout(function () {
    //         console.log(this);
    //     }, 100)
    // }
    // fn.call({ x: 101 })

    // const a = {
    //     fn() {
    //         setTimeout(function () {
    //             console.log(this);
    //         }, 100)
    //     }
    // }
    // a.fn();
    // 情况2
    // class Obj {
    //     fn() {
    //         setTimeout(() => {
    //             console.log(this);
    //         }, 100)
    //     }
    // }
    // const o = new Obj();
    // o.fn();

    function fn() {
        setTimeout(() => {
            console.log(this);
        }, 100)
    }
    fn.call({ x: 101 })
</script>
<script>
    /*
        箭头函数中的 this
        情况1:有function作用域的,this是上层作用域的this
        情况2:没有function作用域的,this是window
    */

    const oBtn = document.getElementById("btn");
    // oBtn.onclick = function () {
    //     console.log(this);
    // }
    oBtn.onclick = () => {
        console.log(this);
    }

    // class Obj {
    //     say = () => {
    //         console.log(this);
    //     }
    // }

    // const Obj1 = new Obj();
    // Obj1.say();

    // const obj2 = {
    //     say: () => {
    //         console.log(this);
    //     }
    // }
    // obj2.say();
</script>

<script>
    /*
        题目1
    */

    // let obj = {
    //     x: 123,
    //     show() {
    //         setTimeout(() => {
    //             console.log(this.x);
    //         }, 100)
    //     },
    // };
    // obj.show();
    // obj.show.call({ x: 101 });

    // let obj = {
    //     fn: () => {
    //         console.log(this, 999);
    //     },
    // };

    // obj.fn();
</script>