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