ES6面向对象
一 概念
```js
// 父类
class People {
// 构造器
constructor (name, age) {
this.name = name;
this.age = age;
}
// 实例方法
eat () {
console.log('吃吃吃');
}
// 类方法
static create () {
console.log('诞生');
}
}
// 子类
class Student extends People {
constructor (name, age) {
// super关键词
super(name, age)
}
}
```
二 代码示范
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>ES6面向对象</title>
</head>
<body>
</body>
<script type="text/javascript">
// 单一对象
let obj = {
name: "ooooobj",
// 方法
fn () {
console.log("fnnnnnnnn");
}
}
console.log(obj.name);
obj.fn();
// 函数
let f = () => {
}
</script>
<script type="text/javascript">
// 多对象 => 创建类
class Person {
// 构造器:创建对象完成初始化操作
constructor (name, age) {
this.name = name;
this.age = age;
}
// 实例方法:只能由对象调用
eat () {
console.log(this.name + '吃吃吃');
}
// 类方法:只能由类调用
static create () {
console.log('诞生');
}
}
let p1 = new Person('zero', 8);
let p2 = new Person('seven', 58);
console.log(p1.age);
p2.eat();
// Person.eat();
Person.create();
// p2.create();
// 继承
class Student extends Person {
constructor (name, age, sex) {
// super指向父级
super(name, age);
this.sex = sex;
}
}
let s1 = new Student("张三", 18, "男");
// 属性的继承
console.log(s1.name, s1.age, s1.sex);
console.log();
// 方法的继承
s1.eat();
// 继承为全继承
Student.create();
</script>
</html>