this指向问题

38 阅读1分钟
 // this指向问题
        // 全局作用域中的this指向  // Window
        console.log(this);
        // 一般函数(非箭头函数)中的this指向
        function add(){
            console.log(this);
        }
        // 只有在函数调用的时候this指向才确定,不调用的时候不知道指向谁
        // this指向和函数在哪调用没有关系,只和谁在调用有关系
        'use strict';
        add(); // undefined -> window (非严格模式下)
        window.add();
        // 特殊点 :构造函数中的this,指向的是构造函数实例化后生成的那个对象

        // 箭头函数中的this指向 (箭头函数没有自己的this)
        // 箭头函数中的this是向上查询的
        const calc = {
            add:()=>{
                console.log(this);
            }
        }
        // window

        // 不适用箭头函数的场景
        // 作为构造函数
        // 需要this指向调用对象的时候
        // 使用arguments,箭头函数中是没有arguments存在的
        function add(){}