继承接受两种继承方式:接口继承和实现继承,接口继承只继承方法签名,而实现继承则继承实际的方法。由于函数没有签名,在 ECMAScript 中无法实现接口继承。 ECMAScript 只支持实现继承,而且其实现继承主要是依靠原型链来实现的。
1.通过原型链实现继承
function Person(){
this.personName = 'person'
}
Person.prototype.getPersonName = function(){
return this.personName
}
function Father(){
this.fatherName = "张珈瑞";
}
Father.prototype.getFatherName = function(){
return this.fatherName
}
Father.prototype = new Person();
var zhangjiarui = new Father();
console.log(zhangjiarui.getPersonName())
2.通过借用构造函数实现继承
function person(){
this.name = 'person'
}
function father(){
person.call(this);
}
var zhangjiarui = new father();
zhangjiarui.name = '张珈瑞'
console.log(zhangjiarui.name) //张珈瑞
var zhangsan = new father();
console.log(zhangsan.name) //person
使用构造函数继承 还有一个好处就是可以在子类型构造函数中向超类型构造函数传递参数
function person(name,sex){
this.name = name
this.sex = sex
}
function father(name,sex){
person.call(this,name,sex);
this.age = '25'
}
var zhangjiarui = new father("张珈瑞","男");
console.log(zhangjiarui.name);
console.log(zhangjiarui.age);
console.log(zhangjiarui.sex);
3.组合继承
function person(){
this.name = 'person'
this.age = 25
}
person.prototype.getPersonName = function(){
var str = '我叫'+this.name+',今年' + this.age
return str
}
function father(name){
//继承属性
person.call(this,name);
}
//继承方法
father.prototype = new person();
var zhangjiarui = new father("张珈瑞");
console.log(zhangjiarui.name);
var zhangsan = new father();
console.log(zhangsan.name);
4.原型继承
function object(o){
function f(){}
f.prototype = o
return new f()
}
var person = {
name:'张珈瑞',
friends:['张三']
}
var zhangjiarui = new object(person);
zhangjiarui.friends.push('李四');
var zhang = new object(person);
zhang.friends.push('王五')
console.log(person.friends)