JavaScript继承的实现

来源:互联网 发布:java 反射获取私有字段 编辑:程序博客网 时间:2024/05/04 03:46

属性使用伪造的方式实现,方法使用原型链的方式实现

function Parent(name)

{

this.name = name ; 

this.nation = “China”;

内存模型:



Parent.prototype.p_say = function()

{

alert(“from parent : ” + this.name );

}

内存模型:


function Chlid( name , age )

{

//使用call,当前这个thisnew Child()这个对象,相当与执行了  new Child().name = //name  ; new Child().nation = “China” ; 

Parent.call(this , name );

}

内存模型:


//下面这两句的顺序一定不能错,否则原型链的指向就错了

Child.prototype = new Parent() ; //Child的原型指向new Parent();

内存模型:


Child.prototype.c_say = function() ;//Child的原型中添加方法,此时原型已经在new Parent()

{

alert(“from Child ” + this.name ) ; 

}

var c1 = new Child(“xxx” , 12);

内存模型:(完整的内存图)


c1.p_say() ;//继承的方法,从图中很清晰的看到,此时c1调用的是Parent Prototype中的P_say

c2.c_say();

alert(c1.nation) ; //继承的属性


原创粉丝点击