js 类基本语法

831 阅读1分钟

创建类class

//创建类
class Star {
    //constructor构造函数,用于传递参数,返回实例对象
    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(); //报错,x,y指向子类,父类中没有接受到值

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调用了父类中的构造函数
        //  super必须写在this之前
        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指向这个方法的调用者