ES5中类与继承
ES5中创建类:function 类名() {}
注意事项:
- 类名要首字母大写
- 静态属性,静态方法,函数都要写在类的外面
- 静态属性的设置:类名.属性名
- 静态方法的设置:类名.方法名
- 函数要写在类的原型下:类名.prototype.函数名
- 静态属性和静态方法的调用:类名.静态属性名/静态方法名()
- 实例属性和函数的调用:先实例化对象,然后 实例化的对象名.实例属性名/函数名 的形式来调用
示例:
// ES5 中的类
function Person(name, age) {
// 实例属性
this.name = name
this.age = age
Person.count++
}
// 静态属性
Person.count = 0
// 实例方法
Person.prototype.showName = function() {
console.log('报上我的大名:' + this.name)
}
// 静态方法
Person.getCount = function() {
console.log('当前有' + Person.count + '人')
}
let p1 = new Person('史迪仔', 2)
console.log(p1)
p1.showName()
console.log(Person.count)
Person.getCount()
let p2 = new Person('莉萝', 6)
console.log(p2)
p2.showName()
console.log(Person.count)
Person.getCount()
打印结果:
ES5中子类继承父类
继承属性- - -父类类名.call(this, 属性名)
继承方法- - -
①先将子类原型指向父类:子类类名.prototype = new 父类类名()
②再将子类的构造函数指向子类自己:子类类名.prototype.constuctor = 子类类名
function Animal(name) {
this.name = name
}
Animal.prototype.showName = function() {
console.log('我的名字就是~' + this.name)
}
// 子类
function Dog(name, age) {
// 继承父类的属性
Animal.call(this, name)
this.age = age
}
// 子类继承父类的方法
Dog.prototype = new Animal()
Dog.prototype.constuctor = Dog
let d = new Dog('墨墨', 2)
console.log(d)
d.showName()
打印结果:
ES6中类与继承
ES6 中类的构建:class
- 创建类- - -class
- 创建构造函数- - -constructor()
- 设置属性- - -方法①构造函数里 this.属性名 = 属性值 的方法
②set get方法设置 - 静态属性- - -static 属性名= 属性值
- 静态方法- - -static 方法名() {、、、}
- 方法- - -方法名() {、、、}
- 静态属性和静态方法的调用- - -可以直接通过 类名.静态属性名/静态方法名 来调用
- 普通属性和方法需要实例化后,通过实例化的对象来调用
示例代码:
// ES6 中的类
class Person {
// 构造函数
constructor(name, age) {
this.name = name
this.age = age
this._color = 0
}
// 静态属性
static address = '地球'
// 静态方法
static getAddress() {
return '我来自~' + this.address
}
// 设置属性,可以进行逻辑处理
set color(val) {
if (val == 1 || val == 2 || val == 3) {
this._color = val
}
}
// 获取属性,可以进行逻辑处理
get color() {
if (this._color == 1) {
return '黑种人'
} else if(this._color == 2) {
return '黄种人'
} else if(this._color == 3) {
return '白种人'
} else {
return '未知'
}
}
// 创建方法
eat(value) {
console.log('吃' + value)
}
}
console.log(Person.address)
console.log(Person.getAddress())
let p = new Person('张三丰', 40)
console.log(p)
p.color = 2
console.log(p.color)
console.log(p)
p.eat('大米')
ES6 中类的继承: extends、super
子类继承父类- - -class 子类类名 extends 父类类名{、、、}
子类继承父类属性- - -super(属性名)
子类继承父类后,可以使用父类中的属性和方法
代码示例:
class Student extends Person {
constructor(name, age, school) {
super(name, age)
this.school = school
}
showSchool() {
console.log('我的学校是~' + this.school)
}
}
let s = new Student('夏目玲子', 18, '景文古田')
console.log(s)
s.showSchool()
s.color = 2
console.log(s.color)
console.log(Student.getAddress())
打印结果: