类中共有的属性和方法this指向问题总结

1.constructor中的this指向的是new出来的实例对象

创建一个公共类 Star 将constructor内的this 赋值给全局变量that 利用全等号判断that与 ldh 实例 是否相等

下面展示一些 内联代码片


   <script>
        var that;
        class Star {
            constructor(uname, age) {
                that = this;
                this.uname = uname;
                this.age = age;

            }
        }
        var ldh = new Star('刘德华')
        console.log(that === ldh);  //true

    </script>

2.自定义的方法,一般也指向的new出来的实例对象

Star公共类中创建一个一定义方法 dance 此方法中的this 也指向new出来的实例对象

下面展示一些 内联代码片

 <script>
        var _that;
        class Star {
            constructor(uname, age) {
                this.uname = uname;
                this.age = age;

            }
            dance(){
                _that=this
                console.log(this);
                
            }
        }
        var ldh = new Star('刘德华')
        ldh.dance();
        console.log(_that === ldh);  //true

    </script>

3.绑定事件之后this指向的就是触发事件的事件源

下面展示一些 内联代码片

当点击按钮就执行自定义方法sing 此时sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数

// An highlighted block
 <button>点击</button>
    <script>
        var that;
        class Star {
            constructor(uname, age) {
                this.uname = uname;
                this.age = age;
               this.btn=document.querySelector('button');
               this.btn.onclick=this.sing
            }
            sing (){
                console.log(this); //<button>点击</button>
                that=this;
            }
         
        }
        var ldh = new Star('刘德华')
     
        console.log(that === ldh);  //false

    </script>

想在sing方法中访问constructor里的数据需要借助于that
先将constructor里的this赋值给全局变量that 再通过that.变量名 在sing方法中访问constructor内的数据
下面展示一些 内联代码片

 <script>
        var that;
        class Star {
            constructor(uname, age) {
                that=this;
                this.uname = uname;
                this.age = age;
               this.btn=document.querySelector('button');
               this.btn.onclick=this.sing
            }
            sing (){
                console.log(this); //<button>点击</button>
                // that=this;
                console.log(that.uname);
                
            }
         
        }
        var ldh = new Star('刘德华')
     
        console.log(that === ldh);  //true

    </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值