es6 class的基础语法,es6 class继承/ es5 call继承描述/使用es6完美继承Array的方法 sort倒序排序console.table()表格生成
//基础语法
function People(name,email){ name, email } class User{ constructor(name,email){ this.name = name; this.email = email; } getinfo(){ console.log(this.name); } static description(){ console.log('I am description --static'); } set urls(values){ console.log(values); this.urlsvalue = values; } get urls(){ return `hello urls ${this.urlsvalue}`; } }
//class 实现继承(附带es5继承方法)
class Animal {
constructor(name){
this.name = name;
this.belly = [];
}
eat(food){
this.belly.push(food);
}
speak(){
console.log('I am lucky')
}
}
class Dog extends Animal{
constructor(name,age){
super(name);
this.age = age;
}
bark(){
console.log('bark bark!');
}
speak(){
console.log('bark bark I am lucky')
}
}
const lucky = new Dog('lucky',2)
console.log(lucky.speak()) //bark bark I am lucky 同个方法会覆盖父类方法
// es5的继承方式比较复杂 // start // function Dog(name,age){ // Animal.call(this,name,age);//在子类的构造函数当中,首先会调用基类的构造函数,es6中直接super()即可。 // this.name = name; // this.age = age; // } // Dog.prototype = new Animal(); //Dog原型对象被指向Animal的实例,constructor会被改变,所以需要下面声明下construcor 指向Dog // Dog.prototype.constructor = Dog;
// end
//es6完美继承Array的方法 start
class MyArray extends Array{
constructor(){
super();
}
}
const colors = new MyArray();
colors[0] = 'red';
console.log(colors.length);
colors.length = 0;
console.log(colors[0]);
//完美继承Array的方法 end
class movieCollection extends Array{ constructor(name,...values){ super(...values); this.name = name } topRated(limit = 10){ return this.sort((a,b) => (a.scores > b.scores) ? -1:1).slice(0,limit); //倒序排序 } } const movies = new movieCollection('Leo', {name:'功夫熊猫',scores:8.7}, {name:'Gongfu',scores:9.7}, {name:'trjei',scores:10}, ) movies.push({name:'ddddd',scores:4}) console.table(movies.topRated()) //会生成一个倒序表格,牛逼了