ES6 从入门到精通 # 21:class 类的用法
Posted 凯小默
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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, age)
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>
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, age)
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>
这里添加方法还可以使用 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, age)
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 类的用法的主要内容,如果未能解决你的问题,请参考以下文章