继承Array
- 原型继承
function Arr(...args){
args.forEach(item=>this.push(item))
this.first = function(){
return this[0]
}
this.max = function(){
return this.sort((a,b)=>b-a)[0]
//注意:sort会改变原数组的顺序
}
}
Arr.prototype = Object.create(Array.prototype)
let a = new Arr(1,2,99,3,4)
console.log(a) //[1, 2, 99, 3, 4]
console.log(a.max()) //99
- 类继承
class Arrc extends Array{
constructor(...args){
super(...args)
}
first(){
return this[0]
}
max(){
return this.sort((a,b)=>b-a)[0]
//注意:sort会改变原数组的顺序
}
}
let b = new Arr(48,9,0,2,2)
console.log(b) //[48, 9, 0, 2, 2]
console.log(b.max()) //48
console.log(b) //[48, 9, 2, 2, 0]
- mixin 混合继承
//mixin 混合继承
class Lesson{
constructor(lessons){
this.lessons = lessons
}
get data(){
return this.lessons
}
}
const data = [
{name:'js',price:200},
{name:'css',price:199},
{name:'python',price:201}
]
let Tool = {
max(key){
return this.data.sort((a,b)=>b[key]-a[key])[0]
}}
let Cont = {
total(key){
return this.data.reduce((t,c)=>t+c[key],0)
}
}
//原型上追加属性
Object.assign(Lesson.prototype,Tool,Cont)
console.dir(Lesson)
let zz = new Lesson(data)
console.log(zz.max('price')) //{name: "python", price: 201}
console.log(zz.total('price')) //600