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
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。