首页 新闻 会员 周边

JavaScript原型上的toString到底是怎么运行的?大家来看看

0
[待解决问题]

alert(nf);     // 5

为什么alert弹出的是5呢?

而console.log(nf);  却是numCount

我把numCount.prototype.toString改成numCount.prototype.toString1

alert就弹出[object Object]..

这是什么原因啊?

function numCount(){
                        var answer = 0;
                    }
                    numCount.prototype.addNumbers = function(num1,num2){
                            this.answer = num1 + num2;
                    }
                    numCount.prototype.toString = function(){
                            return this.answer;
                    }
                    var nf = new numCount();
                    nf.addNumbers(2,3);
                    console.log(nf);  // numCount
                    alert(nf);     // 5
深蓝色梦想的主页 深蓝色梦想 | 初学一级 | 园豆:6
提问于:2012-08-05 00:48
< >
分享
所有回答(3)
0

不知道你是怎么测试的,我这边的测试结果是都是一个numCount对象:

artwl | 园豆:16736 (专家六级) | 2012-08-05 09:49

把numCount.prototype.toString2改成numCount.prototype.toString

支持(0) 反对(0) 深蓝色梦想 | 园豆:6 (初学一级) | 2012-08-05 11:00
0

alert(nf)等价于alert(nf.toString())

乐享程序员 | 园豆:930 (小虾三级) | 2014-04-16 22:12
0

alert()函数内部会调用toString()方法,但是console.log()函数却不是直接调用的toString()方法。

比如console.log()输出多层嵌套的数组的时候,尤其明显。

ThreeTree | 园豆:1490 (小虾三级) | 2015-07-20 09:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册