禁用功能的视图代码(Disable view code of function)

编程入门 行业动态 更新时间:2024-10-26 16:29:26
禁用功能的视图代码(Disable view code of function)

像这样,如果我做了一个功能:

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 defined

You 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.

更多推荐

本文发布于:2023-08-04 18:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1420662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   代码   功能   Disable   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!