ES6中类和对象的注意问题

摘要:在ES中类没有变量的提升,所以必须先定义类,才能通过实例化对象,类里面的共有属性和方法一定要加this使用,类里面的this使用问题:

实用类的三个注意点:

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://shenqiku.cn/article/FLY_9248