class的使用
通过class创建类(实质是函数)
class Person {
static type='animal'
constructor(name){
this.name = name
}
getName(){
return this.name
}
}
class Chinese extends Person {
constructor(name, age){
super(name)
this.name = name
this.age = age
}
}
分析
对js原型链熟悉的人应该能很快理解(ps: js:原型、继承总结)
- 原型链的
constructor
指向函数本身,所以constructor
里写的就是函数体内容 -
getName
相当于Person.prototype.getName
-
static
是个提案,相当于Person.type='animal'
-
super()
就是构造继承的Person.apply(this)
源码
通过转成原始代码应该是这样的
function Person(name) {
this.name = name
}
Person.type = 'animal'
Person.prototype = {
constructor: Person,
getName: function(){
return this.name
}
}
function Chinese (name, age) {
Person.apply(this, arguments)
this.age = age
}
// 组合继承
Chinese.prototype = new Person()
// 寄生组合继承
(function(){
function Mid(){}
Mid.prototype = Person.prototype
Chinese.prototype = new Mid()
Chinese.prototype.constructor = Mid
})()
Chinese.prototype.constructor = Chinese