JavaScript、ES6中类的this指向问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button>按钮</button>
    <script>
        // this指向问题
        var that;
        var _that;

        class Fa {
        //constructor 里面的this指向的是 创建的实例对象(ff)
            constructor(x, y){
                that = this;
                this.x = x;
                this.y = y;
                this.btn = document.querySelector('button');
                this.btn.onclick = this.sing;
            }
            sing(){
                // this指向的是 btn这个按钮 因为这个按钮调用了这个函数
                console.log("11111111111");
                console.log(that.x);
                // that 里面存储的是constructor里面的this
                
                // console.log(this.x);

            }
            sum(){
            //这个sum 里面的this指向的是实例对象ff 因为ff调用了这个函数(this指向sum方法的调用者ff) 
                _that = this;
                console.log(this.x + this.y);
            }
        }
        var ff = new Fa(1,2);
        console.log(that === ff); // true
        // console.log(ff);
        // // Fa {x: 1, y: 2}
        ff.sum();
        console.log(_that === ff); // true

    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/sylys/p/11654602.html