es6的面向对象

es6的classes

构造方法:constructor。new的时候调用
class Student{
    constructor (name,age){
        this.name=name;
        this.age=age;
    }
    run(){
        return this.name;
    }
}
let xs = new Student("姜姜",23);
console.log(xs.name);
console.log(xs.age);

function Vehicle (name,age){
    this.name = name;
    this.age = age;
}
Vehicle.prototype.name = function name(){
    return this.name;
};
var jj = new Vehicle ("吴建",24);
console.log(jj.name);

get set
class Student{
    constructor (name,age){
        this.name =name;
        this.age=age;
    }
    run(){
        console.log("我会飞");
    }
    get xm(){
        return this.name +"123";
    }
    set xm(value){
        this.name =value;
    }
    static shangxue (){
        console.log("去上学");
    }
}
let xs = new Student("姜姜",25);
console.log(xs.xm);
xs.xm="姜姜";
console.log(xs.xm);
Student.shangxue();
//get:获取加赋值。
//set:设置。
//static:静态方法|类方法。
//set和get的方法名相同,并且能够同名

方法重载|方法覆盖:
class Student{
    constructor (name,age){
        this.name =name;
        this.age=age;
    }
    run(){
        console.log("我会飞");
    }
}
let xs = new Student("姜姜",25);

class Teacher extends Student{
    constructor (name,age,sex){
        super(name,age);
        this.sex=sex;
    }
    eat(){
        console.log(this.name +"is eating")
    }
    run(){
        super.run();
        console.log("我想高飞");
    }
}
var ls = new Teacher("吴建","30","男");
ls.run();//我会飞 我想高飞;
注释:虽然子类继承了父类的run方法,可是子类会把父类的方法给覆盖掉,这个就是方法覆盖

继承export
命名规范 —name 私有属性
static静态方法 方法覆盖
ES6 中有 class 语法。值得注意是,这里的 class 不是新的对象继承模型,它只是原型链的语法糖表现形式。
extends 容许一个子类继承父类,须要注意的是,子类的 constructor 函数中须要执行 super() 函数。
关键字 class, extends, super
特色
  1. 非声明提高(hoisted) 和let同样javascript

  2. 自动处于严格模式java

  3. 须要new, 不然会抛错es6

  4. 重写类名和方法会抛错函数

  5. 有get set 方法this

  6. 能够指定方法为static 。只能在class内部使用。prototype

相关文章
相关标签/搜索