DISABLE VIEW CODE OF FUNCTION JAVASCRIPT

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
 1028  View(s)
Ratings:
Rate this:
Hi Everyone!

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?

Thanks in advance!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Disable view code of function javascript

    Hi Lois!

    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.

    I hope it resolve your problem!

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!