JS 继承
1 原型链继承
//父类
function Person(name,age){
this.name = name || 'unknow'
this.age = age || 0
}
//子类
function Student(name){
this.name = name
this.score = 80
}
//继承
Student.prototype = new Person();
Student.prototype.constructor = Student;
var stu = new Student('lucy');
console.log(stu.name); //lucy --子类覆盖父类的属性
console.log(stu.age); // 0 --父类的属性
console.log(stu.score); // 80 --子类自己的属性
*原型继承共享引用类型(方法)*
共享方法可以,因为方法本身代码不变,就是被共享的. 但有些引用类型自身变化,如下
//父类
function Person(){
this.hobbies = ['music','reading']
}
//子类
function Student(){
}
//继承
Student.prototype = new Person();
Student.prototype.constructor = Student;
var stu1 = new Student();
var stu2 = new Student();
stu1.hobbies.push('basketball');
console.log(stu1.hobbies); // ["music", "reading", "basketball"]
console.log(stu2.hobbies); // ["music", "reading", "basketball"]
2 构造函数继承
*构造函数不共享引用类型和方法*
//父类
function Person(){
this.hobbies = ['music','reading']
}
//子类
function Student(){
Person.call(this);
}
var stu1 = new Student();
var stu2 = new Student();
stu1.hobbies.push('basketball');
console.log(stu1.hobbies); // ["music", "reading", "basketball"]
console.log(stu2.hobbies); // ["music", "reading"]
*构造函数可以给父类传参*
//父类
function Person(name){
this.name = name;
}
//子类
function Student(name){
Person.call(this,name); //传参Person(name)
}
var stu1 = new Student('lucy');
var stu2 = new Student('lili');
console.log(stu1.name); // lucy
console.log(stu2.name); // lili
3 组合继承
某些引用类型属性使用构造函数继承不共享,方法使用原型链继承共享。
不论是构造函数还是原型链, 基本类型都是不共享的(基本类型与引用类型赋值的区别)
//父类
function Person(name){
this.hobbies = ['music','reading'];
}
Person.prototype.say = function(){
console.log('i am a person');
}
//子类
function Student(name){
Person.call(this); //构造函数继承(继承属性)本地hobbies
}
Student.prototype = new Person(); //原型继承(继承方法) 原型链hobbies和say
Student.prototype.constructor = Student;
//其实是本地hobbies比原型链的hobbies优先,实现组合继承
var stu1 = new Student('lucy');
var stu2 = new Student('lili');
stu1.hobbies.push('basketball');
console.log(stu1.hobbies); // ["music", "reading", "basketball"]
console.log(stu2.hobbies); // ["music", "reading"]
console.log(stu1.say === stu2.say); // true