6.1 Javascript的继承是基于原型的继承
6.1.1属性的继承
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("meng",21,"js");
consloe.log(t)
6.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要使用Person里的sayName方法,把Person的原型赋给Teacher
Teacher.prototype.sayName=function(){
console.log(this.age)
}
Teacher.prototype.constructor=Teacher;//line12 因为把Person赋给了Teacher,所以Teacher的构造属性(constructor)也变成了Person的构造属性
var t=new Teacher("meng",21,"js");
var p=new Person("name",19)
console.log(t)
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("meng",21,"js")
console.log(t.constructor)
t.sayName();
t.sayAge();