ES6新语法测试

<!DOCTYPE html>
<script>
class Base{
    constructor(...arg){
        [this.num1,this.num2=1]=arg;
    }
    add(...arg){ //注意js 没有真正意义上的重载,只能根据参数的不同进行判断分流
        if(arg.length<=1){
            return this.num1+this.num2;
        }
        else{
            return arg[0]+arg[1];
        }
    }
}
class Complex extends Base{// js 只能实现单继承,如果使用多继承,可以使用Mixin模式(基于object copy来实现)。参见Es6标准入门(第三版)P436
    constructor(...arg){
        let [complex1=[1,0],complex2=[1,0]]=arg; //这里多写一句,是因为js构造函数要求super出现在所有this之前
        super(complex1[0],complex2[0]);  //传默认参数
        [this.complex1=[1,0],this.complex2=[1,0]]=[complex1,complex2];
    }
    add(){
        return[super.add(),this.complex1[1]+this.complex2[1]] ;
    }
}
let base=new Base();
console.log(base.add()); //undefined+1 = NaN
let base1=new Base();
console.log(base1.add(20,21)); //41

let complex=new Complex();
console.log(complex.add());  //[2,0]
let complex1=new Complex([1,2],[5,7]);
console.log(complex1.add());  //[6,9]
</script>

1、继承

js 只能实现单继承,如果使用多继承,可以使用Mixin模式(基于object copy来实现)。参见Es6标准入门(第三版)P436

2、多态

  • 重载: js无重载,只能通过参数的个数进行判断
  • 虚函数:关于方法是自动覆盖父类的相同方法,如果想要某个父类函数没法被调用,可在内部抛出个异常。
原文地址:https://www.cnblogs.com/xunhanliu/p/11187958.html