09类拓展-es6
# 类拓展
# 一、创建类
class Person{
constructor(name) {//构造器
this.name = name//实例化属性
}
age = 18//实例化属性
static hobby = "打游戏"//静态属性
}
Person.prototype.sex = "男"//原型属性
let p = new Person("小明")
Person.hobby//打游戏
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
[!cogs]
%accordion% 这种是活了 %accordion%
class Person {//类
constructor(name, age) {//构造函数
this.name = name//实例属性
this.age = age
}
}
let p = new Person("张三", 18)
console.log(p); //Person {name: "张三", age: 18}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
%/accordion%
%accordion% 这种age已经写死了 %accordion%
class Person {//类
constructor(name) {//构造函数
this.name = name//实例属性
}
age = 18//实例化属性
}
let p = new Person("张三")
console.log(p); //Person {age: 18, name: "张三"}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
%/accordion%
%accordion% 语法糖 %accordion%
class Person {//类
constructor(name) {//构造函数 ——对象上调用
this.name = name//实例属性 ——对象上调用
}
age = 18//实例化属性
static hobby = "打游戏"//静态属性,——在类上调用
}
Person.prototype.sex = "男"//原型属性 ——对象上调用
let p = new Person("张三")
console.log(p); //Person {age: 18, name: "张三"}
console.log(Person.hobby); //打游戏
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
%/accordion%
# 二、类继承
class Person{
constructor(name) {
return this.name = name
}
say(){
return "呵呵"
}
}
class Student extends Person{
constructor(name,age){
super(name)//继承父类的构造函数方法
this.age = age//student类自己独有的属性
}
saying(){
return super.say()+"哈哈"//调用父类的原型方法
}
}
let s = new Student("小明",18)
console.log(s.saying())//呵呵哈哈
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[!cogs]
%accordion% 1️⃣😀 %accordion%
class Person {
constructor(name) {
this.name = name
}
age = 18
}
let p = new Person("张三")
class Student extends Person {
}
let s = new Student()
console.log(s); //Student {age:18, name: undefined}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
%/accordion%
%accordion% 2️⃣😂 %accordion%
class Person {
constructor(name) {
this.name = name
}
age = 18
}
let p = new Person("张三")
class Student extends Person {
}
let s = new Student("李四")
console.log(s); //Student {age:18, name: "李四"}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
%/accordion%
%accordion% 3️⃣🤣 %accordion%
class Person {
constructor(name) {
this.name = name
}
age = 18
}
let p = new Person("张三")
class Student extends Person {
constructor(name) {
super(name) //可以更改属性
}
}
let s = new Student("李四")
console.log(s); //Student {age:18, name: "李四"}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%/accordion%
编辑 (opens new window)
上次更新: 2022/04/24, 13:33:34