method.toString()在Firefox中添加'use strict',而不是在IE或Chrome中添加。
Javascript代码:
'use strict';
var myMethod = function foo(){return 1};
result = myMethod.toString();
console.log(result);
结果:
是否有可能以某种方式定义指令'use strict'应该在toString()中包含/排除?
答案 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;
答案 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);