method.toString()exclude / include' use strict'

时间:2014-11-25 12:31:31

标签: javascript cross-browser tostring

method.toString()在Firefox中添加'use strict',而不是在IE或Chrome中添加。

Javascript代码:

'use strict';
var myMethod = function foo(){return 1};
result = myMethod.toString();
console.log(result);

Plunker to reproduce it

结果:

  • Chrome 39.0:“function foo(){return 1}”
  • Internet 11:“function foo(){return 1}”
  • Firefox 33.1:“function foo(){”use strict“; return 1}”

是否有可能以某种方式定义指令'use strict'应该在toString()中包含/排除?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用它来确定严格模式并插入'它进入toString结果:

var strictMode = (function() { return !this; })() ? '"use strict"; ' : '';
var result = myMethod.toString()
                 .replace(/"use strict";/, '') // FF prevent doubling
                 .replace(/{/, '{'+strictMode);

查看更新的Plunker或查看代码段



'use strict';

var strictMode = (function() { return !this; }()) ? '"use strict"; ' : '';
var myMethod = function foo(){return 1};

$(function(){
  $("#function").append(
      myMethod.toString()
       .replace(/"use strict";/, '') // to prevent a double 'use strict' in firefox
       .replace(/{/, '{'+strictMode) );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello stackOverflow!</h1>
<h2>My Function to String</h2>
<p id="function"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做:

'use strict';
 var myMethod = function foo(){return 1};
var result = myMethod.toString().replace('\n"use strict";\n','');// exclude the use strict
 console.log(result);