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
相关文章推荐
- javascript 高级——基于原型链和伪装的继承
- javascript基于原型链的继承及call和apply函数用法分析
- 详解JavaScript中基于原型prototype的继承特性
- 高级javascript---原型和原型继承
- JavaScript高级内容笔记:原型链、继承、执行上下文、作用域链、闭包
- 基于JavaScript实现继承机制之原型链(prototype chaining)的详解
- JavaScript基于原型链的继承
- JavaScript面向对象(3)——原型与基于构造函数的继承模式(原型链)
- 原型模式和基于原型继承的JavaScript对象系统
- 【JavaScript高级程序设计】读书笔记之二 —— 理解对象的原型、继承
- 6、JavaScript高级之继承一(原型链)
- javascript中的继承(JS基于原型链的继承),以及JS中的call和apply函数
- js面向对象、原型及继承(javaScript高级程序设计第3版)
- javascript基础之十(基于原型实现类的继承)
- javaScript 基于原型的对象继承
- javascript 基于原型的知识--如何实现继承
- javascript基于原型的继承
- javascript高级:原型与继承
- JavaScript基于原型链的继承
- JavaScript基于原型的继承