Home > DeveloperSection > Forums > Disable view code of function javascript
lois waisbrooker
lois waisbrooker

Total Post:70

Points:494
Posted on    April-04-2013 1:47 AM

 JavaScript JavaScript 
Ratings:


 1 Reply(s)
 769  View(s)
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!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-04-2013 7:05 AM

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!

Don't want to miss updates? Please click the below button!

Follow MindStick