ES6新增的创建类的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// ES6中增加的class
// 其实是我们function 定义构造函数的语法糖
//ES6之前创建类的方法
// function People(name, age, sex) {
// this.name = name;
// this.age = age;
// this.sex = sex;
// }
// People.prototype.intro = function () {
// console.log("大家好,我的名字是" + this.name + "我的年龄是" + this.age + "我是一个" + this.sex + "孩子")
// }
// class是关键字 用于定义类
// 关键字后面跟的是类名
// 类名后面跟的是类体
class People {
constructor(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
// 新增了静态方法 类可以调用静态方法
static offset() {
console.log("我是People这个类的静态方法")
}
// 存取器 写的时候写的是函数的写法 但其实定义的是一个属性
get getName() {
console.log("执行我了,我是取器")
return this.name;
}
set setName(value) {
console.log('执行我了,我是存器')
this.name = value;
}
//原型上的方法
intro() {
console.log("大家好,我的名字是" + this.name + "我的年龄是" + this.age + "我是一个" + this.sex + "孩子")
}
}
var p1 = new People("渣渣辉", 29, "男");
p1.intro();
var p2 = new People("古天乐", 18, "男")
p2.intro();
People.offset();
// 存取器测试 明明带了圆括号 却不能调用
// console.log(p1.getName);
p1.setName = "hahaha"
</script>
</body>
</html>