原型链构造函数 & class构造函数
ES5,通过构造函数生成对象function A(name,age){
this.name = name
this.age = age
}
// 在A的prototype属性上定义一个test方法,即A生成的实例化对象的原型对象上的方法
A.prototype.test = function(){
return this.name +''+ this.age
}
var a1 = new A('Mandy',25)
console.log(a1.test()) // Mandy 25
ES6中,引入了class关键字,上面代码等价于下面:
class B{
constructor(name,age){
this.name = name
this.age = age
}
test(){
return this.name+''+this.age
}
}
let b1 = new B('Mandy',25)
console.log(b1.test()) // Mandy 25
class中的静态方法static
如果在函数前加上static,代表这是一个静态方法。父类的静态方法可以被子类继承,但实例对象无法访问。class C{
//没有写上constructor,默认会生成一个空的构造函数
static foo(){
console.log(100)
}
}
let c1 = new C()
c1.foo() //error
C.foo() //100
继承extends
class可以通过extends关键字继承。如果子类通过extends继承父类,那么在子类的constructor构造函数必须调用 super,并且要在使用 this 之前执行它。class D{
constructor(name,gender){
this.name = name
this.gender = gender
}
static foo(){
console.log(100)
}
}
class E extends D{
constructor(name,gender,age){
super(name,gender)
// 挂载子类独有的属性
this.age = age
}
}
let e1 = new E('Mandy','female',25)
e1.foo() //error
E.foo() //200
//说明父类的静态方法可以被子类继承,但实例对象无法访问
子类挂载独有属性
实例会优先继承构造其本身的子类的独有属性class A{
constructor(){
this.name = 'A'
}
sayName(){
console.log(this.name)
}
}
class B extends A{
constructor(){
super()
this.name = 'B'
}
}
let obj = new B()
console.log(obj.sayName()) //'B'
class C extends A{
constructor(){
super()
}
}
let obj2= new C()
console.log(obj.sayName()) //'A'