class类使用注意点

143 阅读1分钟

结论:

1.在ES6中类没有变量提升,所以必须先定义类,再通过类实例化对象

2.类里面共有的属性和方法在使用的时候都要加 this

3.类里面this指向问题:

  • constructor构造函数里面的this指向类的实例对象
  • 方法里面的this指向该方法的调用者
<body>
    <button>点击</button>
    <script>
        // 写在这里会报错 在ES6中没有变量提升
        //   let ldh = new Father('llll')//报错Cannot access 'Father' before initialization
        //   ldh.sing();
        
        let that;
        let that_;
        class Father{
            constructor(uname,age){
                this.uname = uname;
                this.age = age;
                this.btn = document.querySelector('button');
                //🌸1.加上小括号就是立即调用,所以不加 2.要加this!!!!
                this.btn.onclick = this.sing;
                console.log(this);              //🌸指向的是ldh这个实例对象
                that = this;
            }
            sing(){🌸//btn调用了这个方法,所以这里的this指向btn
                console.log('hi');
                console.log(this);//指向的是btn这个按钮,因为这个按钮调用了sing这个方法
                console.log(this.uname);//undefined🌼因为这里的this是btn,btn里面没有uname这个属性
                console.log(that.uname);//刘德华🌻这里因为that已经在前面赋值指向constructor的this,等于是指向实例对象
            }
            dance(){
                console.log(1);
                that_ = this;
            }
            
        }

      let ldh = new Father('刘德华',11)
      console.log(that === ldh);//true,验证了这个constructor里面的this指向实例对象
      ldh.dance();
      console.log(that_ === ldh);//true 前提是ldh调用了dance这个方法
    //ldh.sing()//如果加上这,sing()里面的this.uname=刘德华
        
    </script>
</body>
  • 关于sing这个方法在这里指向btn的解释:

-- 特殊情况下this 指向的不再是constructor里面的this,但是想要使用constructor里面的this,这时候可以在外面声明一个全局变量,that,that=constructor的this,这that这个全局变量就可以到处使用了

截屏2022-06-29 20.26.38.png