请教js的prototype和constructor的问题
ztree吧
全部回复
仅看楼主
level 4
arko2002 楼主
function Person(name)
{
this .name=name;
};
Person.prototype.from=function ()
{
alert('I come from prototype.' );
}
var father= new Person( 'js' );
alert(father.constructor);//结果是:function Person(name) {...};
function SubPer(){}
SubPer.prototype=father;
SubPer.prototype.constructor=SubPer;
alert(father.constructor);//结果是:function SubPer(){};
我的问题是这的father.constructor怎么指向了SubPer函数呢?
2012年08月27日 03点08分 1
level 11
SubPer.prototype=father;
先指定了 SubPer 的prototye 是 father,也就是是 Person
SubPer.prototype.constructor=SubPer;
因为执行了前面的语句,所以这句话就相当于:Person.constructor = SubPer
因此导致了你说的将结果。
但如果修改为 SubPer.constructor=SubPer;
那么结果是不一样的了
2012年08月27日 05点08分 2
感谢能在百忙之中得到你的指点,还有不明之请指。SubPer.prototype.constructor=SubPer; [$1]用ffbug查看Person.constructor是Person(name),而father.constructor和 SubPer.constructor是SubPer();
2012年08月28日 03点08分
level 4
arko2002 楼主
当把SubPer.prototype.constructor=SubPer;换成Person.constructor = SubPer;Person.constructor的是SubPer(),而father和SubPer的constructor仍然是Person(name),alert(SubPer.prototype.constructor)和alert(father.constructor)是function Person(name) {...};
2012年08月28日 03点08分 3
level 4
arko2002 楼主
加SubPer.prototype.constructor=SubPer; father的constructor变成了是function SubPer() {};不加的话是function Person() {};为什么呢?
2012年08月28日 03点08分 4
level 11
请你要理解一下几个概念:
1、 SubPer 和 Person 是 function,所以 SubPer.constructor 和 Person.constructor 是相同的,都是 Function...
2、 在你没有修改 prototype 的情况下, function 的原型的 构造器指向的是自身,也就是说 SubPer.prototype.constructor 是 SubPer 自身这个 function
因此 SubPer.constructor 和 SubPer.prototype.constructor 是完全不一样的
3、你的代码 SubPer.prototype=father; 让 SubPer.prototype 指向了 father;最后一句:
SubPer.prototype.constructor=SubPer 其实就等于 father.constructor=SubPer; 所以就出现了最终的结果。
但要记住,Person.constructor = SubPer 这个是不会影响 father 的 constructor 的。

2012年08月29日 09点08分 5
1