Javascript的继承是基于原型的继承
1-1 属性的继承
# call 实现属性的继承
function Person(name,age){
this.name = name;
this.age = age
}
function Teacher(name,age,skill){
Person.call(this,name,age) // Person(name,age)中的this指向window,需要改变this指向
this.skill = skill // this指向 Teacher构造函数的实例对象
}
var t = new Teacher("zhang",18,"js")
console.log(t);
1-2 方法的继承
function Person(name,age){
this.name = name;
this.age = age
}
Person.prototype.sayName = function(){
console.log(this.name);
}
function Teacher(name,age,skill){
Person.call(this,name,age)
this.skill = skill
}
+Teacher.prototype = Person.prototype;
+Teacher.prototype.constructor = Teacher;
Teacher.prototype.sayAge = function(){
console.log(this.age);
}
var t = new Teacher("zhang",18,"js")
console.log(t);
+t.sayName()
t.sayAge()
1-2-1 es5中实现继承的方法
function Person(name,age){
this.name = name;
this.age = age
}
Person.prototype.sayName = function(){
console.log(this.name);
}
function Teacher(name,age,skill){
Person.call(this,name,age)
this.skill = skill
}
Teacher.prototype = Object.create(Person.prototype,{
constructor:{
value:Teacher
}
})
Teacher.prototype.sayAge = function(){
console.log(this.age);
}
var t = new Teacher("zhang",18,"js")
console.log(t);
console.log(t.constructor);
t.sayName()
t.sayAge()