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

来源:互联网 发布:淘宝手机壳好评语30字 编辑:程序博客网 时间:2024/05/23 01:58

今天查阅资料发现有资料说我们在使用原型链(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(){    }的代码块中,所以这种继承方式也就不能传递参数给构造方法!

原创粉丝点击