学习javascript遇到的一个问题。

wyman25 wyman25 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我在学习js继承特性中,在尝试call与prototype比较的时候,遇到了这个问题:

<script type="text/javascript">
var father=function(){
this.name="father";
}
var child=function(){
child.prototype=new father();
}
var son=new child();
alert(child.prototype.name);
alert(son.name);
</script>

IE8和chrome第一个弹出框是"father",但第二个弹出框却是undefined。百思不得其解:既然第一个弹出框是"father",也就是说child.prototype的确是new father()这个对象,但为什么son并没有获得father.name属性呢?然后我将“child.prototype=new father();”这句放在child函数外面,变成:

<script type="text/javascript">
var father=function(){
this.name="father";
}
var child=function(){
//child.prototype=new father();//放到child外面执行
}
child.prototype=new father();
var son=new child();
alert(child.prototype.name);
alert(son.name);
</script>

结果两个弹出框都是"father"。为什么这语句在child里面执行,son就不能继承到father(即使son的构造函数child的prototype已经是new father())?为什么放在外面就可以? 是不是域的问题?求解答!!!
我在js版的积分不多,请不要嫌弃
...全文
评论 18
收藏 已收藏
分享
返回顶部
wyman25
JavaScript 87,984 成员 224,681 内容