创建类class
class Star {
constructor(uname) {
this.uname = uname
}
sing(song) {
console.log('唱歌'+song)
}
say(word) {
console.log('说话'+word)
}
}
var ldh = new Star('刘德华');
console.log(ldh.uname);
ldh.say('你好');
ldh.sing('冰雨');
类的继承
class Father {
constructor(x,y) {
this.x = x
this.y = y
}
money() {
console.log(100);
}
sum() {
console.log(this.x + this.y)
}
}
class Son extends Father{
constructor(x,y) {
this.x = x;
this.y = y;
}
}
var son = new Son(1,2);
son.money();
son.sum();
super关键字
class Father {
constructor(x,y) {
this.x = x
this.y = y
}
money() {
console.log(100);
}
sum() {
console.log(this.x + this.y)
}
}
class Son extends Father{
constructor(x,y) {
super(x,y)
this.x = x
this.y = y
}
substract() {
console.log(this.x - this.y)
}
}
var son = new Son(1,2);
son.money();
son.sum();
son.substract()
es6注意点
- 在es6中类没有变量提升,所以必须先定义类
- 类里面的共有的属性和方法一定要加this使用
- 类里面的this指向问题,constructor里面的this指向实例对象,方法里面的this指向这个方法的调用者