2023/1/15 JS-函数中的this指向问题

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

1 this是什么?

  • 任何函数本质上都是通过某个对象来调用的如果没有直接指定就是window
  • 所有函数内部都有一个变量this
  • 它的值是调用函数的当前对象

2 如何确定this的值?

<script>
    function Person(color) {
        console.log(this)
        this.color = color;
        this.getColor = function () {
            console.log(this)
            return this.color;
        };
        this.setColor = function (color) {
            console.log(this)
            this.color = color;
        };
    }

    Person("red"); //this是谁? window

    const p = new Person("yello"); //this是谁? p

    p.getColor(); //this是谁? p

    const obj = {};
    //调用call会改变this指向-->让我的p函数成为`obj`的临时方法进行调用
    p.setColor.call(obj, "black"); //this是谁? obj

    const test = p.setColor;
    test(); //this是谁? window  -->因为直接调用了

    function fun1() {
        function fun2() {
            console.log(this);
        }

        fun2(); //this是谁? window
    }

    fun1();//调用fun1
</script>

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6