您的位置:首页 > Web前端 > JavaScript

javascript 高级——基于原型链的继承

2014-01-03 15:00 309 查看
function Parent(){
this.ParentName = "parent";
}
Parent.prototype.ParentValue = function(){
alert(this.ParentName);
}
function Children(){
this.ChildrenName = "children";
}
//将Children的原型指向Parent的一个实例,完成继承
Children.prototype = new Parent();
Children.prototype.ChildrenValue = function(){
alert(this.ChildrenName);
}
var c1 = new Children();
var p1 = new Parent();
c1.ParentValue();
c1.ChildrenValue();

结果:parent

children

这是一个基于原型链的继承方式,当然很重要的还是它的内存模型

当刚刚建立函数的时候,Parent和Children各自指向自己的原型



此时Parent和children没有任何关系

再下一步,重写继承链关系,将children的Prototype属性指向Parent的一个实例,这样parent空间里面的属性就会复制到实例中一份,而实例的_prop_属性也会指向

原型对象,从拥有其方法,这样就完成了继承





当调用ParentVale()的时候,首先在自己空间里面寻找ParentValue方法,没有找到,然后调用prototype找到原型的指向,发现原型中

没有这个方法,但是原型中有_prop_属性,于是调用_prop_的指向找到Parent prototype,找到这个方法,然后在方法中调用this.parentName的时候

再次寻在,发现在自己空间中没有,但是在原型的指向中找到了parentName

缺点

function Parent(parentName){
this.parentName = parentName;
}
function Children(ChildrenName){
this.ChildrenName = ChildrenName;
}
Children.prototype = new Parent("parent"); //仅仅只能在此处来为父类的属性赋值
//有很大的局限性
还有一个问题,如果父类中有引用类型,而在子类中对其进行应用,并赋值的,就会改变其,这样的方式就像是将属性仍然定义在原型中一样

function Parent(parentName){
this.parentName = parentName;
this.arr = ["h","d"]; //注意这个地方的数组类型
}
Parent.prototype.say = function(){
alert(this.arr.join(","));
}
function Children(ChildrenName){
this.ChildrenName = ChildrenName;
}
Children.prototype = new Parent("parent");
var c1 = new Children("张三");
var c2 = new Children("李四");
c1.arr.push("a");
c1.say();
c2.say();

结果:h,d,a
h,d,a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: