Marvin3
Marvin3

Reputation: 6051

How to prevent JS code from being parsed/evaluated by compiler?

I have a module with a lot of JS code in it. Module is created like so:

(function (root, factory) {
  // root === window
  root.MyModuleName = factory();
})(this, function () {
  'use strict';
  var MyModuleName = function() {
    // A lot of code here that I don't want to be parsed or evaluated
    // until MyModuleName constructor is executed.
    //
    // For example:
    // var a = { d: 123 };
    // var b = function() { return 45; };
    // this.someMethod = function() { b() + a.d };
    // ...
  };
  return MyModuleName;
});

All methods & properties are inside MyModuleName closure and (I thought) they should be parsed only after MyModuleName() is executed.

After user clicks on some button I create an instance of MyModuleName and execute some method:

someButton.onclick = function() {
  // I want compiler to parse and evaluate JS code only here
  var myModule = new MyModuleName();
  console.log(myModule.someMethod());
};

Even though MyModuleName constructor is executed() only after click, code inside it is evaluated when JS file loads (I can see it in Chrome dev tools timeline).

How to make sure compiler evaluates code only after click, not after JS file loads?

Upvotes: 2

Views: 194

Answers (1)

Quentin
Quentin

Reputation: 943939

You can't. The JS engine has to evaluate the code to create the function before it can assign the function anywhere.

Upvotes: 1

Related Questions