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

5次阅读

共计 929 个字符,预计需要花费 3 分钟才能阅读完成。

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
            }
        }
正文完
 0