es5 的三种继承方式
一、构造函数继承( 缺点是:原型上的方法或者属性,无法继承)
function Fn(){
this.name = "zhangsan",
this.age = 12
this.eat = function(){
console.log("eat")
}
}
Fn.prototype.sleep = function(){
console.log("sleep")
} // 无法继承
function F(){
console.log(this)
Array.prototype.join.call(obj,'-') // 上下文模式 call 和 apply
Array.prototype.join.apply(obj,['-'])
Fn.call(this)
}
var fn = new Fn()
console.log(fn)
var f = new F()
console.log(f.sleep())
二、 原型继承
共用一个原型对象,导致谁修改原型对象的值,其余对象都会被更改
function Fn(){
this.name = "zhangsan"
this.age = 12
this.color = ["yellow", "pink"]
this.eat = function(){
console.log("eat")
}
}
Fn.prototype.sleep=function(){
console.log("sleep")
}
function F(){}
F.prototype = new Fn()
var f = new F()
var f1 = new F()
f.color.push("black")
console.log(f1.color)// color=['yellow','pink','black']
三、组合方式
function Fn(){
this.name = "zhangsan"
this.age = 12
this.color = ["yellow", "pink"]
this.eat = function(){
console.log("eat")
}
}
function F(){
Fn.call(this) // this指向 Fn()
}
F.prototype = Object.create(Fn.prototype)
// F.prototype = Fn.prototype.constructor === Fn
F.prototype.constructor = F
var f = new F()
var f1 = new F()
f.color.push("black")
console.log(f1.color) //color =["yellow", "pink"]
function FCC(){}
console.log(f instanceof FCC)
console.log(f instanceof Fn)
es6继承
1.通过extends 关键字来继承
2.子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工,如果不调用super方法,子类就得不到this对象。因此,只有调用super之后,才可以使用this关键字。
class People{
constructor(name,age,skin){
this.name = name,
this.age = age
this.skin = skin
}
eat(){
console.log("eat")
}
sleep(){
console.log("sleep")
}
speak(){
console.log("speak")
}
}
class Student extends People{
constructor(name,age,skin,id,classs){
super(name,age,skin)
this.id = id
this.classs = classs
}
study(){
console.log("study")
}
}
var stu = new Student("zhangsan",12,"yellow",110,'一年级01班')