为了账号安全,请及时绑定邮箱和手机立即绑定

请问一个js继承中的问题?

请问一个js继承中的问题?

慕盖茨0887536 2017-05-22 18:10:57
function extend(Father,Son){ var F=function(){}; F.prototype=Father.prototype; Son.prototype=new F(); Son.prototype.constructor=Son; Son.uber=Father.prototype; } function Grandfather(){} Grandfather.prototype.toString=function(){ alert(this)}; function Father(){}; extend(Grandfather,Father); function Son(){}; extend(Father,Son); var p=new Son();p.toString();这段代码会报错Uncaught RangeError: Maximum call stack size exceeded;可我将Grandfather.prototype.toString的alert改为console.log就可以正常运行了,后来我把toString改下名又可以正常alert出 了,这是为什么
查看完整描述

1 回答

?
qq_冲哥_0

TA贡献40条经验 获得超30个赞

当你调用alert (this)的时候,它默认会toString()方法,把this 转换成字符串,进行输出,你用下面的代码把toString 重写了,所以它会调用你写的toString() 方法,而你的toString方法中是 alert(this), 所以又会调用toString方法,造成了循环引用,最后导致内存不足,报错Uncaught RangeError: Maximum call stack size exceeded;

Grandfather.prototype.toString=function(){

alert(this)

};


查看完整回答
反对 回复 2017-05-22
  • 1 回答
  • 1 关注
  • 1184 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信