1.在OO语言中,继承的方式支持两种:接口继承与实现继承。
接口继承:继承方法签名,实现继承:继承实际方法。
但是 在ECMAScript中没有方法签名,无法实现接口继承,只支持实现继承,而实现继承主要是依靠原型链来实现。
2.原型链基本思路:
利用原型让一个引用类型继承另一个引用类型的属性和方法。
每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数想指针(constructor),而实例对象都包含一个指向原型对象的内部指针(__proto__)。如果让原型对象等于另一个类型的实例,此时的原型对象将包含一个指向另一个原型的指针(__proto__),另一个原型也包含着一个指向另一个构造函数的指针(constructor)。假如另一个原型又是另一个类型的实例……这就构成了实例与原型的链条。
3.基本图谱
4.动手验证:
<html>
<body>
<script>
function son(name,age){
father.call(this,name,age);
}
son.prototype=Object.create(father.prototype);
son.prototype.constructor = son;
function father(name,age)
{
this.name=name;
this.age=age;
this.say=function(){
console.log("my name is"+this.name);
}
}
father.prototype.show=function()
{
console.log(this.name +" is "+this.age);
}
var a=new son("sadf",24);
console.log(a);
a.show();
var b=new father("sdf",90)
b.show();
b.say();
console.log(b);
</script>
</body>
</html>
输出如下:
可以看出 分为两块继承 ,一是对象本身继承(用call实现),与原型继承(用object.create 实现);
去掉 son.prototype=Object.create(father.prototype); son.prototype.constructor = son; 原型继承这一条,会报错
可以看出,a的原型里没有show方法;
es6 继承
function a(){
class Father{
constructor(name, age){
this.name = name;
this.age = age;
}
show(){
console.log(`我叫:${this.name}, 今年${this.age}岁`);
}
};
class Son extends Father{};
let son = new Son('金角大王', 200);
son.show();//return 我叫:金角大王, 今年200岁
console.log(son)
};
a();
输出: