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