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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM