class Foo { constructor(){ this.a = 'a' } gougou(){ return 'dididada' } jiji(temp){ if(!isNaN(temp)){ return Number(temp)+20 }else{ return 'Hello |' + this.a + '| ' + temp; } } } let p = new Foo; // console.log(p) // console.log(p.jiji(50)) // console.log(p.jiji('bobo')) // console.log(p.gougou()) //继承 class Ary extends Array{ constructor(){ super();//必须要加才能用this this.a = '10'; this.b = '20' } fn(arg){ if(this.length > 4){ //使用super调用继承的数组方法排序,只要length>4就不会再添加项而是去排序 super.sort(function(a,b){ return a-b }) }else{ if(arg < 1){ return this.push(this.a) }else if(arg == 1){ return this.push(1) }else{ return this.push(this.b) } } } } let aa = new Ary;
aa.fn(-1);
aa.fn();
aa.fn(20);
aa.fn(1)
aa.fn(3)
class SuperArray extends Array { shuffle(){//洗牌算法 for(let i = this.length-1;i>0;i--){ const j = Math.floor(Math.random()*(i+1)); [this[i],this[j]] = [this[j],this[i]];//数组结构赋值 } } } let a = new SuperArray(1,2,3,4,5); console.log(a) a.shuffle(); console.log(a)