es6中新增class很像我学的C#中的class,可以面向对象
在es6中 class不存在变量提升,所以需要先定义再使用。
在原生的js中新增方法是在对象上的prototype新增方法
function Person(name,age) {
this.name = name;
this.age=age;
}
Person.prototype.say = function(){
return "我的名字叫" + this.name+"今年"+this.age+"岁了";
}
var obj=new Person("laotie",88);//通过构造函数创建对象,必须使用new 运算符
console.log(obj.say());//我的名字叫laotie今年88岁了
新建一个函数,在prototype上新增函数,通过new关键字指向另外一个对象
new关键字执行过程:
1.当使用了构造函数,并且new 构造函数(),后台会隐式执行new Object()创建对象;
2.将构造函数的作用域给新对象,(即new Object()创建出的对象),而函数体内的this就代表new Object()出来的对象。
3.执行构造函数的代码。
4.返回新对象(后台直接返回);
现在通过ES6的class扩展方法:
<script>
// extends为继承关键字
// constructor 为构造函数关键字
// super为继承基类的方法关键字
class myarry extends Array {
constructor(name, ...tems) {
super(...tems);//为了获得代表Array this值
this.name = name;
}
add(item) {
this.push(item);
}
orderby(limit = 8) {//默认参数值等于8
return this.sort((a, b) =>
(a.scores > b.scores )? -1 : 1 )
}
}
const movies = new myarry('info',
{ name: 'lily', scores: 80 },
{ name: 'Sasa', scores: 85 },
{ name: 'Neo', scores: 90 }
)
movies.add({ name: 'Susan', scores: 60 });//调用myarry方法
</script>