JavaScript Example Method for Defining Global Objects

  • 2021-07-10 18:40:56
  • OfStack

This article illustrates how JavaScript defines global objects. Share it for your reference, as follows:


!function (factory) {
  factory(window['Hi'] = {
    __a: function () {
      console.log('Hi.__a');
    },
    __b: function () {
      console.log('Hi.__b');
    },
    __c: function () {
      console.log('Hi.__c');
    }
  });
}(function (Hi) {
  if (typeof Hi === undefined) {
    Hi = {};
  }
  Object.defineProperty(Hi, 'appName', {
    get: function () {
      return 'this is app name.';
    }
  })
});
console.log(Hi.appName);//this is app name.
Hi.__b();//Hi.__b

Pass the object (Hi) definition function as an argument (factory) to the immediate execution function through the immediate execution function


!function (factory) { }();

In an immediate execution function, the object to be defined is passed as an argument to the immediate execution function's argument function.

The following can also implement the same object definition:


var myObj = myObj || {};
(function (myObj) {
  myObj.__a = function () {
    console.log('myObj.__a');
  };
  myObj.name = 'this is myObj.name';
})(myObj);
console.log(myObj.name);//this is myObj.name
myObj.__a();//myObj.__a

These definition methods are relatively independent and can be saved and used as functional modules of the Party Capital.

Similar to Jquery plug-in writing.

More readers interested in JavaScript can check the topics of this site: "javascript Object-Oriented Introduction Tutorial", "JavaScript Search Algorithm Skills Summary", "JavaScript Data Structure and Algorithm Skills Summary", "json Operation Skills Summary in JavaScript", "JavaScript Error and Debugging Skills Summary" and "JavaScript Mathematical Operation Usage Summary"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: