Examples of how JavaScript defines global objects and javascript examples

Source: Internet
Author: User

Examples of how JavaScript defines global objects and javascript examples

This example describes how JavaScript defines global objects. We will share this with you for your reference. The details are 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) defined function as a parameter (factory) to the immediate execution function by immediately executing the Function

!function (factory) { }();

In the immediate execution function, the object to be defined is passed as the parameter of the Parameter Function for immediate execution of the function.

The same object definition can also be implemented as follows:

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.namemyObj.__a();//myObj.__a

These definition methods are relatively independent and can be stored and used as the functional modules of the party's capital.

Similar to Jquery plug-in writing.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.