JavaScript 代码未在函数内执行

JavaScript code not executed inside a function

为什么app.init()函数里面的代码没有执行?

(function () {
  
  console.log('loaded here');

  function ready(callbackFunction){
    if (document.readyState != 'loading')
      callbackFunction(event)
    else
      document.addEventListener("DOMContentLoaded", callbackFunction)
  }

  var app = function (options) { 
    var app = this,
          version = 1.00;
 
    app.init = function () {
      console.log('not loaded here');
      console.log(window);
    }

    app.init();
  };
  
  ready(event => {
    console.log('dom is loaded');
    window.myApp = function (opt) { return new app(opt); };
  });
  
})();

您永远不会将 window.myApp 作为函数调用,而现在您只是在声明它。改为以下,

(function () {
  
  console.log('loaded here');

  function ready(callbackFunction){
    if (document.readyState != 'loading')
      callbackFunction(event)
    else
      document.addEventListener("DOMContentLoaded", callbackFunction)
  }

  var app = function (options) { 
    var app = this,
          version = 1.00;
 
    app.init = function () {
      console.log('not loaded here');
    }

    app.init();
  };
  
  ready(event => {
    console.log('dom is loaded');
    var opt = {};
    window.myApp = new app(opt);
  });
  
})();