像这样,如果我做了一个功能:
function a() { alert("Hello!") }我不希望你能够像以下一样查看代码:
eval(a)返回所有代码但是
eval(a())返回警报
在做eval时(一)我希望它不返回代码,什么都没有?
Like this, if I made a function:
function a() { alert("Hello!") }I don't want you to be able to view the code like:
eval(a)Returns all the code but
eval(a())Returns the alert
When doing eval(a) I want it to not return the code, just nothing how?
最满意答案
始终将代码封装在IIFE(立即调用的函数表达式)中,这样您就不会将变量泄漏到全局范围:
(function(){ function a() { alert("Hello!") } // more stuff... }()); console.log(eval(a)); //=> Uncaught ReferenceError: a is not defined您还可以使用一个小技巧来使用bind隐藏功能代码:
var a = function a() { alert("Hello!") }.bind(); console.log(eval(a)); //=> function () { [native code] }无论何时考虑使用eval ,请三思而后行,这可能是一种更好的方法。 如果您只想运行该函数,只需执行a() 。 那里不需要eval 。
Always encapsulate your code in an IIFE (Immediately Invoked Function Expression) so you don't leak variables to the global scope:
(function(){ function a() { alert("Hello!") } // more stuff... }()); console.log(eval(a)); //=> Uncaught ReferenceError: a is not definedYou can also use a little trick to hide the function code with bind:
var a = function a() { alert("Hello!") }.bind(); console.log(eval(a)); //=> function () { [native code] }Whenever you think about using eval, think twice, there's probably a better way to do it. If you just want to run the function, just do a(). No need for eval there.
更多推荐
发布评论