关于javascript:JavaScript笔记面向对象编程2this的指向问题

class Star {
            constructor(uname, age) {
                this.name = uname;
                this.age = age;
                this.sing(); //留神这里用了this  一般函数也是能够放入constructor的 因为sing是一个类外面的 类外面的话基本上每一处都要用this
               // 除了constructor前面的圆括号
            }
            sing() {
                console.log(this.name);

            }
        }
        var ldh = new Star('刘德华', 19);
        ldh.sing();
        //这个也能够打印 记住new是调用constructor 
        //super是调用父类

        //this的指向问题
        //constructor外面的this 指向创立的实例 ldh
        //因为  var ldh=new Star('刘德华',19); 创立的实例就是ldh 
        //所以constructor外面的this指向ldh


        //而办法外面的this 指向这个办法的调用者 button
        //因为以上的这两句话 constructor中的 this和一般函数中的this是不同的 所以能够申明一个全局变量that 在constructor中写 that=this  而后在一般函数外部 将本来的 this替换成that

        var ldh = new Star('刘德华', 19);//这一行会主动调用constructor 
        //所以如果constructor内有打印的函数 会间接打印

通过全局变量that来解决this的指向问题。

        var that;
        class Star {
            constructor(uname, age) {
                that = this;             //!!!!!!留神这行 //
                this.name = uname;
                this.age = age;
                this.sing(); //留神这里用了this 基本上每一处都要用this 除了constructor前面的圆括号
                this.btn = document.querySelector('button');
                this.btn.onclick = this.sing;


            }
            sing() {
                console.log(this.name);    //sing是一个函数 这里调用者是btn 所以sing指向btn
                console.log(that.uname);  //这里的that等于ldh
            }
        }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理