关于prototype Chain创建对象和实现继承

本文通过实验探讨了JavaScript中使用原型链实现继承时构造函数参数传递的问题,并得出Child.prototype=newParent()不能放在构造函数内的结论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天查阅资料发现有资料说我们在使用原型链(prototype chain)的方式实现继承的时候,是不能实现传递参数的构造方法的,觉得这块很乱就做了几个实验!并发表下实验结果和大家一起讨论:

1.首先从我们使用prototype来创建对象说起

      function Parent()

{

Parent.prototype.name="zhaogao";

}

var p=new Parent();

alert(p.name);

      function Parent()

{

}

Parent.prototype.name="zhaogao";

var p=new Parent();

alert(p.name);

效果是一样的,也就是说Parent.prototype.name="zhaogao";代码的位置对我们创建这个属性是没有影响的。

带参数的情况:

      function Parent(name)

{

Parent.prototype.name=name;

}

var p=new Parent("zhaogao");

alert(p.name);

也是可以实现我们的目的


2.prototype用于继承

对于Parent不带参数的情况

      function Parent()

{

Parent.prototype.name="zhaogao";

}

//Parent.prototype.name="zhaogao";

function Child(){   }

Child.prototype=new Parent();

var c=new Child();

alert(c.name);

无论Parent.prototype.name="zhaogao";在Parent构造方法的哪个部分都可以实现继承的功能


对于Parent带参数的情况:

        function Parent(name)

{

Parent.prototype.name=name;

}

function Child(){   }

Child.prototype=new Parent("zhaogao");

var c=new Child();

alert(c.name);

也是可以实现继承的


上面的这些都可以正常工作


但是一旦我将Child.prototype=new Parent("zhaogao");或者Child.prototype=new Parent();放到Child的构造函数中,就不能正常工作了

即一旦

function Child()
{
Child.prototype=new Parent();
//Child.prototype=new Parent("zhaogao");
}

     无论我的Parenet的Parent.prototype.name="zhaogao"在构造方法内部和外部,以及是否带参数都不能正常实现继承

所以得到结论:Child.prototype=new Parent()不能在function Child(){    }的代码块中,所以这种继承方式也就不能传递参数给构造方法!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值