1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6</head> 7<body> 8 <button>按钮</button> 9 <script> 10 // this指向问题 11 var that; 12 var _that; 13 14 class Fa { 15 //constructor 里面的this指向的是 创建的实例对象(ff) 16 constructor(x, y){ 17 that = this; 18 this.x = x; 19 this.y = y; 20 this.btn = document.querySelector('button'); 21 this.btn.onclick = this.sing; 22 } 23 sing(){ 24 // this指向的是 btn这个按钮 因为这个按钮调用了这个函数 25 console.log("11111111111"); 26 console.log(that.x); 27 // that 里面存储的是constructor里面的this 28 29 // console.log(this.x); 30 31 } 32 sum(){ 33 //这个sum 里面的this指向的是实例对象ff 因为ff调用了这个函数(this指向sum方法的调用者ff) 34 _that = this; 35 console.log(this.x + this.y); 36 } 37 } 38 var ff = new Fa(1,2); 39 console.log(that === ff); // true 40 // console.log(ff); 41 // // Fa {x: 1, y: 2} 42 ff.sum(); 43 console.log(_that === ff); // true 44 45 </script> 46</body> 47</html>
JavaScript、ES6中类的this指向问题
Stella981
2021-10-11
1125 0 0
点赞
收藏
评论区
加载中...