13.this

This

  • 函数在执行时,JS解析器每次都会传递一个隐藏的参数,这个参数就是this
  • this会指向一个对象
    • this所指向的的对象会根据函数调用方式的不同而不同
      • 以函数形式调用时,this指向的是window
      • 以方法的形式调用时,this指向的是调用方法的对象
      • . . .
<script>
        function fn1() {
            console.log("fn1打印", this);
        }
        fn1(); //fn1打印 Window

        const obj1 = { name: "孙悟空" }
        obj1.test = fn1
        obj1.test() //fn1打印 Object { name: "孙悟空", test: fn1() }

        const obj2 = { name: "猪八戒", test: fn1 }
        obj2.test() //fn1打印 Object { name: "猪八戒", test: fn1() }
</script>

this的应用场景

我们在对象中声明一个name属性,并且打印输出name的值。要求name的值改变,打印结果也跟着改变。

  • 这里的this存在于test函数里面,而test又是对象obj3和obj4的方法,所以调用test就相当于调用this。
  • 以方法的形式调用this,this指向的就是其所在的对象。(谁调它它就指向谁)
        const obj3 = {
            name: "沙和尚",
            test: function () {
                console.log(this.name, this);
            }
        }
        obj3.test() //沙和尚 Object { name: "沙和尚", test: test() }

        const obj4 = {
            name: "唐三藏",
            test: function () {
                console.log(this.name, this);
            }
        }
        obj4.test() //唐三藏 Object { name: "唐三藏", test: test() }

箭头函数的this

箭头函数:

  • ([参数])=> 返回值

例子:

  • 无参箭头函数:( )=>返回值
  • 一个参数的:a => 返回值
  • 多个参数的:(a,b)=>返回值

 

  • 只有一个语句的函数:( )=>返回值
  • 只返回一个对象的函数:( )=>({. . .})
  • 有多行语句的函数:( )=>{ . . . return xxx }

 

箭头函数没有自己的this,它的this由外层作用域决定

  • 如下面的箭头函数fn2它的外层作用域是window,所以this永远指向window
  • 箭头函数的this和它的调用方式无关
<script>
        // 函数声明
        function fn1() {
            console.log("fn1-->", this);
        }
        // 箭头函数
        const fn2 = () => {
            console.log("fn2-->", this);//this 永远指向window
        }

        const obj = {
            name: "monkey King",
            fn1, //这里采用缩写,fn1:fn1
            fn2
        }

        obj.fn1() //fn1--> Object { name: "monkey King", fn1: fn1(), fn2: fn2() }
        obj.fn2() //fn2--> Window
</script>

情景一

<script>
        const obj1 = {
            test() { //缩写 test:function()
                function t() {
                    console.log("t-->", this);
                }
                t(); //调用t函数
            }
        }
        obj1.test(); //t--> Window
</script>

这里明明是以方法的形式调用的test啊,为什么this不是obj1呢?

test的确是以方法的形式调用的,但是我们真正调用的是t函数,在方法体中t是以window的形式调用的。所以this指向window。

情景二

const obj2 = {
    test() { //缩写 test:function()
        const t = () => {
            console.log("t-->", this);//this的外层函数是test,test的this是Object(对象)
        }
        t(); //调用t函数
    }
}
obj2.test(); //t--> Object { test: test() }

根据箭头函数的特点, 箭头函数的this和它的调用方式无关,只和它的外层作用域有关。

  这里箭头函数内部调用了this,但箭头函数没有自己的this。所以向外找找到了test函数,test函数的this是obj2对象(也就是{}里面的内容)。

为什么说test函数的this是obj2的对象呢?

  应为执行语句是obj2.test()

 

posted @ 2022-11-10 17:05  莫扎特03  阅读(17)  评论(0编辑  收藏  举报