实用类的注意事项

三个注意点:

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

2.类里面的共有属性和方法一定要加this使用

3.类里面的this使用问题:

4.constructor里面的this指向实例化对象,方法里面的this指向这个方法的调用者

<script>
        var that;
        var _that;
        class Star {
            // constructor 里面的this 指向的是 lbw
            constructor(uname , age) {
                that =  this;

                console.log(this);
                
                this.uname = uname;
                this.age = age;
                this.dance();
                //this.sing();
                this.btn = document.querySelector('button');
                this.btn.onclick = this.sing;
            }
            sing() {
                //这个sing方法里面的this 指向的是 btn这个按钮 因为这个按钮调用了这个函数
                console.log(that.uname);
            }
            dance() {
                _that = this;//这个dance里面的this 指向的是实例对象ldh因为ldh调用了这个函数
                console.log(this);
                
            }
        }
        var lbw = new Star('刘德华');
        console.log(lbw ===that);//
        console.log(lbw ===_that);
        
        //1.在ES6类没有变量提升,所以必须先定义类,才能通过类实例化对象
        //2.类里面的共有的 属性和方法 一定要加到this里使用。
    </script>

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/qiujie-prion/p/12989632.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程