<!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>