javascript 之 面向对象【继承】

时间:2023-03-09 07:36:34
javascript 之 面向对象【继承】

继承:函数没有签名,无法实现接口继承。ECMAScript只支持实现继承

1/原型链

回顾:构造函数、原型和实例的关系?

回:每个构造函数都有一个原型对象。原型对象都包含一个指向构造函数的指针。实例都包含一个指向原型对象的内部指针。

案例分享:
function FatherType()
{
this.F_PanDuan = true;
}
FatherType.prototype.getFatherValue= function () {
return this.F_PanDuan;
} function ChildType()
{
this.C_PanDuan = false;
}
ChildType.prototype = new FatherType();
ChildType.prototype.getChildValue = function ()
{
return this.C_PanDuan;
}
var instance = new ChildType();
alert(instance.getFatherValue()); //true
案例分析:FType 和CType分别有一个属性和方法,其中CType继承了FType
理解难点在于:每个构造函数都有一个原型对象。原型对象都包含一个指向构造函数的指针。实例都包含一个指向原型对象的内部指针。
扩展分析:原型搜索机制。当读取模式访问一个实例属性时,先在实例中搜索该属性,若没有该属性则搜索实例的原型。
那么这里会有三个步骤:1/搜索实例 2/搜索ChildType.prototype 3/搜索FatherType.prototype

javascript 之 面向对象【继承】

2/确定原型与实例的关系

(1)instanceof操作符

alert(instance  instanceof  Object) //true  (其中Object 还可以是FatherType,ChildType 返回都为true)

(2)isPrototypeOf()

alert(Object.prototype.isPrototypeOf(instance)) //true  (其中Object 还可以是FatherType,ChildType 返回都为true)

3/谨慎地定义方法

接着上面地例子:加一句 //重写父类型中的方法  ChildType.prototype=getFatherValue=function(){ return false};  结果: alert( instance.getFatherValue())  //false

还需要注意的是:ChildType.prototype指针已经指向了FatherType,那么此时ChildType.prototype 就不能指向其他方法或对象,否则就不是指向FachterType构造函数

4/原型链的问题:

(1)包含引用类型值得原型属性都会被所有实例共享

案例:
function F_Type(){
this.colors={'red','green','blue'}
}
function C_Type(){}
C_Type.prototype=new F_Type();
var instancel=new C_Type();
instancel.colors.push('black')
alert(instancel.colors) //'red','green','blue','black' var instancel2=new C_Type()
instancel2.colors.push('black')
alert(instancel.colors) //'red','green','blue','black'

(2)在创建子类型得实例时,不能向父类型的构造函数中传递参数