在类外调用类中的方法
class Star {
constructor(uname, age){
this.uname = uname;
this.age = age;
}
sing (){
console.log(this.uname);
}
}
var ldh = new Star('刘德华');
ldh.sing();
在ES6中类没有变量提升,所以必须先定义类,才能通过类实例化对象,类里面的共有属性和方法一定要加上this使用,表示特指本类中的属性和方法
<button>点击</button>
<script>
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.uname);
}
}
var ldh = new Star('刘德华');
//ldh.sing();
</script>