0
点赞
收藏
分享

微信扫一扫

ES6 从入门到精通 # 21:class 类的用法


说明

ES6 从入门到精通系列(全23讲)学习笔记。

es5 造类

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>function Person(name,) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function() {
return this.name;
}
Person.prototype.getAge = function() {
return this.age;
}

let kaimo = new Person("kaimo", 313);
console.log(kaimo);
console.log(kaimo.getName());
console.log(kaimo.getAge());</script>
</body>
</html>

ES6 从入门到精通 # 21:class 类的用法_javascript

class 造类

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>class Person {
// 实例化的时候会被立即调用
constructor(name,) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
}

let kaimo = new Person("kaimo", 313);
console.log(kaimo);
console.log(kaimo.getName());
console.log(kaimo.getAge());</script>
</body>
</html>

ES6 从入门到精通 # 21:class 类的用法_实例化_02

这里添加方法还可以使用 ​​Object.assign()​​ 一次性向类中添加多个方法。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>class Person {
// 实例化的时候会被立即调用
constructor(name,) {
this.name = name;
this.age = age;
}
}

Object.assign(Person.prototype, {
getName() {
return this.name;
},
getAge() {
return this.age;
}
})

let kaimo = new Person("kaimo", 313);
console.log(kaimo);
console.log(kaimo.getName());
console.log(kaimo.getAge());</script>
</body>
</html>

ES6 从入门到精通 # 21:class 类的用法_javascript_03


举报

相关推荐

0 条评论