1. Es5
function Person(name){
this.name = name
this.eat = "水果"
}
Person.prototype.address ={
location:'北京'
}
// Son.prototype.__proto__ = Person.prototype // 共享公共属性 但__proto__被废除了
// Object.setPrototypeOf(Son.prototype,Person.prototype) //等同于上一种
Son.prototype= Object.create(Person.prototype,{ // 寄生式组合继承(第二个参数是将constructor指向自身)
constructor:{value:Son}
})
// Son.prototype = new Person() 不推荐 会污染父类
function Son(name){
this.age = 20;
Person.call(this,name)
}
Son.prototype.hobby = function(){
console.log("writeJs")
}
let s = new Son("lucy")
console.log(s.name,'xx')
console.log(s.address,'///')
2.Es6
// 静态属性 私有属性 共有属性
class Person{
static flag(){ //静态属性 类上面的属性
return 123
}
age = 18 // 实例上的属性
constructor(name){ // 为了传参 所以写constructor 私有属性:实例上面
this.name = name
this.eat = "ss"
}
address(){
console.log("北京")
}
drink(){
console.log("父 喝水")
}
}
//let address = p.address address() // 单独调用 this 不存在
// console.log(Person.flag()) 静态属性是通过类去寻找的 不是实例
class Son extends Person{
constructor(name){ // 写constructor 一定写super
super(name) // super 默认指向父类 相当于es5 Person.call(this,name)调用
// super = Super.prototype 指向父类的原型
}
drink(){
super.drink() // 子类原型的方法指向 父类的原型
console.log("子 喝水")
}
}
let p = new Son()
p.drink()
// console.log(Son.flag()) // 静态方法继承在子类上 不是子实例p.flag()