es6,class的使用+继承
- 话不多说直接上代码
实例属性和静态属性
function Person(name, age) {
this.name = name
this.age = age
}
Person.info = 'aaa'//静态属性
var p1 = new Person('小明', '18')
console.log(p1,Person.info)
console.log('-----------------------------------------------------------');
class Animal {
//这是类中的构造器
//每一个类都有一个构造器,如果没有手动指定,内部会自动有空的构造器,类似于 constructor() {}
constructor(name, age) {
this.name = name
this.age = age
}
static info = 'eee'//推荐方法
}
const a1 = new Animal('大黄', 3)
console.log(a1,Animal.info);
- 上面的方式我们分别,用传统方式和class方式,创建了构造函数,且实例化了,且在浏览器中的表现方式也是通过prototype 的,从本质上来看是没有区别的,
- constructor 构造器 来实现this.xxx = xxx
- static 实现静态属性的添加
实例方法和静态方法
function Person(name, age) {
this.name = name
this.age = age
}
Person.info = 'aaa'//静态属性
var p1 = new Person('小明', '18')
Person.prototype.say = function () {
console.log('is Person 实例方法')
}
Person.show = function () {
console.log('Person的静态方法')
}
console.log(p1,Person.info)
p1.say()//实例方法
Person.show()// 静态方法
console.log('-----------------------------------------------------------');
/* 注意
1.在class { } 区间内,只能写 构造器 静态方法和静态属性、实例方法
*/
class Animal {
constructor(name, age) {
this.name = name
this.age = age
}
//动物的实例方法
jiao () {
console.log('Animal 的实例方法')
}
static info = 'eee'//推荐方法
static show() {
console.log('Animal 的静态方法')
}
}
const a1 = new Animal('大黄', 3)
console.log(a1,Animal.info);
a1.jiao()
Animal.show()
- 实例方法和今天方法的定义也是一样的,实例方法直接定义,静态方法 用
static来修饰
class继承
我们可以看到 Preson 是作为American和Chinese 的父类,他们都继承了 Preson的属性,但是Chinese
有自己的IDnumber,需要定义自己的constructor,但是如果我们在给子类定义constructor 要在开头加入
super(), 且要接收实例化传过来的参数
class Person {
constructor (name, age) {
this.name = name
this.age = age
}
sayhello () {
console.log('父类的hello方法')
}
}
// class 类中,可以使用extends 关键字,实现,子类继承父类
// 语法 class 子类 extends 父类{}
class American extends Person {
constructor (naem, age) {
/**问题1: 为什么一定要在 constructor 中调用 super ?
* 因为,一个子类,通过extends 关键字继承了父类,那么,在这个子类的 constructor 构造函数中,必须优先调用一下 super()
* 问题2:super 是什么东西?
* super是一个函数,而且他是父类的 构造器,子类的super,其实就是父类中的 constructor 构造器的一个引用
* 问题3:为什么调用了 super(),之后name和age都变成了undefined?
* 实例化的时候 要把 参数 name age 传递进去 给 constructor再给super
*/
super(naem, age)
}
}
const a1 = new American('Jack', '20')
console.log(a1)
a1.sayhello()
class Chinese extends Person {
constructor (name, age, IDnumber) {
super(name, age)
// 语法规范 在子类中, this 只能放在super 之后
this.IDnumber = IDnumber
}
}
const c1 = new Chinese('张三', '23', '123456')
console.log(c1)
c1.sayhello()
- 注意点
- super() 置前
- constructor (name, age, IDnumber) 传递自己的参数给 super
参考书 es6入门
本文深入探讨ES6中Class的使用,包括实例属性、静态属性、实例方法、静态方法及Class继承。通过代码示例讲解如何使用constructor构造器、static关键字,并演示子类如何通过super调用父类构造器。
2197

被折叠的 条评论
为什么被折叠?



