es6通过extends关键字继承
注意:super必须在子类this之前调用
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y)
}
}
//子类继承父类的加法方法,并且扩展减法方法
class Son extends Father {
constructor(x, y) {
//super必须在子类this之前调用
super(x, y)
this.x = x
this.y = y
}
subtract() {
console.log(this.x - this.y)
}
}
let obj1 = new Father(5, 6)
obj1.sum()
let obj2 = new Son(4, 3)
obj2.sum()
obj2.subtract()
输出:11 7 1
构造函数
实例成员:构造函数内部通过this添加的成员,只能通过实例化的对象来访问
静态成员:构造函数本身添加的成员,只能通过构造函数来访问
function Star(name,age){
this.name = name
this.age = age //name,age,sing 属于实例成员
this.sing = function(){
console.log("唱歌")
}
}
Star.sex = "男" //sex属于静态成员
prototype
每个构造函数都有prototype
一般情况下公共属性定义到构造函数里面,公共方法放到原型对象上
节省 内存
function Star(name,age){
this.name = name
this.age = age
}
Star.prototype.sing = function(){
console.log("唱歌")
}
对象原型 proto
对象都会有一个原型__proto__,指向构造函数的prototype对象
constructor
__proto__和prototype里都有一个constructor属性,它指回构造函数本身
constructor主要用于记录该对象引用了那个构造函数,它可以让原型对象从新指向原来的构造函数