介绍
本文是在学习ES6时做的一些学习笔记,所有的笔记请查看:ES6 学习笔记
原型对象方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
function User(name,email){
this.name = name;
this.email = email;
}
// 在原型对象中添加方法
User.prototype.info = function(){
console.log(`hi,i am ${this.name}`)
}
const codecasts = new User('codeCasts','[email protected]')
// 可以对原型对象方法进行重写
User.prototype.info = function(){
console.log(`hi,i am ${this.name},my email is ${this.email}`)
}
</script>
</body>
</html>
类 class
1、类是一种特殊函数,但不存在函数提升
2、类有两种声明方式,一种类的声明,二是类的表达式方式
3、只能通过new 关键字调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
// 类的声明,类也是一种特殊函数
//
let methodName = 'info';
class User{
// 构造函数
constructor(name,email){
this.name = name;
this.email = email;
}
info(){
console.log(`hi,i am ${this.name},my email is ${this.email}`)
}
// 计算属性的方式定义方法
[methodName](){
console.log(`hi,i am ${this.name},my email is ${this.email}`)
}
// 类的静态方法
static description(){
console.log('I am a user of castcasts');
}
// 类的set方法
set github(value){
this.githubName=value;
}
// 类中get方法
get github(){
return `https://github.om/${this.geihubName}`;
}
}
// 类的表达式,定义方式和函数类似,是一种特殊的函数
// 该方法中的函数声明与上述定义类的方式相同
const User=class{
}
const codecasts = new User('codeCasts','[email protected]');
codecasts.info();
</script>
</body>
</html>
类的继承:
1、使用super();
2、子类方法覆盖同名的基类的方法
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
class animal{
constructor(name){
this.name=name;
this.belly = [];
}
eat(food){
this.belly.push(food);
}
speak(){
console.log(`I am ${this.name}`)
}
}
class Dog extends animal{
constructor(name,age){
super(name);// 调用基类的构造函数
this.age = age;
}
bark(){
console.log('barl bark');
}
// 该方法会覆盖基类的speak()函数
speak(){
console.log(`barl bark! I am is ${this.name}`)
}
}
</script>
</body>
</html>
class 来扩充Array():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
// 使用 class 扩展 Array
class MyArray extends Array{
constructor{
super();
}
}
const colors= new MyArray();
colors[0]= 'red';
console.log(colors.length); // 输出 1
// 此处扩展一个数组,增加一个name属性
class movieCollection extends Array{
constructor(name,...item){// 此处的...items代表剩余参数
// 此处的super代表new Array()
super(...items); // 此处的...items代表扩展运算符,将数组扩展
this.name=name;
}
add(movie){
this.push(movie);
}
topRated(limit=10){
return this.sort((a,b)=>(a.scores > b.scores)?-1:1)
.slice(0,limit);
}
}
//根据上述扩展数组,添加的数组数据
const movies=new movieCollection('favorite movies',
{name: 'The croods',scores: 8.7},
{name: 'The croods',scores: 8.7},
{name: 'The croods',scores: 8.7},
)
// 调用add()方法添加数据
mmovie.push( {name: 'The croodss',scores: 8.7});
</script>
</body>
</html>