Javascript中函数的toString()方法

简述

    The toString() method returns a string representing the source code of the function.

    简译之,Javascript的toString()方法返回一个代表函数源代码的字符串。

句法

    function.toString(indentation) 或 Function.prototype.toString()

详细描述

     The Function object overrides the toString method inherited from Object; it does not inheritObject.prototype.toString. For Function objects, the toString method returns a string representation of the object in the form of a function declaration. That is, toString decompiles the function, and the string returned includes the function keyword, the argument list, curly braces, and the source of the function body.

JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

 

 先来看看默认情况下使用toString()会返回什么

<script type="text/javascript">
                   function sum(a){
                        var t = 1;
                             return sum;
                   }
                   alert((sum(1)).toString());
</script>

 

    运行代码1后,浏览中弹出框的内容是:

function sum(a){
     var t = 1;
     return sum;
}

    这里也证明了函数的toString() 方法默认下返回的是该函数的源代码(字符串格式)。

 

   根据上面的详细描述,函数的toString()方法可以被override,即重写。我们来重写该方法:

 

<script type="text/javascript">
         function sum(a){
              var t = 1;
              sum.toString = function(){
                    return "override toString method";
               }
               return sum;
         }
        alert((sum(1)).toString());
</script>

   

    运行代码2后,浏览器弹出框中的内容是: 

override toString method

   从运行结果中得出结论,toString()方法已经被重写。

 

 

学以致用:

    问题:

     创建一个函数sum,使得:sum(a)(b) = a+b; sum(a)(b)…(c)=a+b+…+c; 成立。

 

 <script type="text/javascript">
                   function sum(a){
                        var sum = a;
                             function t(b){
                                sum += b;
                                     return t;
                             }                 
                            t.toString = function() { return sum }
                            return t;
                   }
                   alert(sum(1)(2)(-1));
                   alert(sum(1)(2)(-1)(7));
         </script>

    在这个例子中,最后是使用toString方法成功的返回了sum值,解答问题完毕。

 

 

    参考资料:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值