简体   繁体   中英

Javascript Module Pattern / Prototype Pattern : can't figure out this code

I trying to create a simple google maps plugin. I'm following a tutorial but i can't figure out this block of code. Anyone could explain me this code ?

(function(window, google) {

   var Mapster = (function() {
       function Mapster(element, opts) {
           this.gMap = new google.maps.Map(element,opts);
       }

       Mapster.prototype = {
           zoom: function(level) {
               //some code here
           }
       };

       return Mapster;
   }());

  Mapster.create = function(element, opts) {
      return new Mapster(element, opts);
 };

 window.Mapster = Mapster;

}(window, google));
// http://benalman.com/news/2010/11/immediately-invoked-function-expression/
(function (window, google) {
    // local `Mapster` IIFE
    var Mapster = (function () {
        // local `Mapster` constructor function
        function Mapster(element, opts) {
            this.gMap = new google.maps.Map(element, opts);
        }

        Mapster.prototype = {
            zoom: function (level) {
                //some code here
            }
        };

        return Mapster;
    }());

    // convenience function to create new instances of `Mapster`
    Mapster.create = function (element, opts) {
        return new Mapster(element, opts);
    };

    // exposing `Mapster` globally
    window.Mapster = Mapster;

    // passing in `window` & `google` as params to the IIFE
}(window, google));

// usage:

var mapster = Mapster.create(someEl, {});

console.log(mapster.gMap);

Hopefully the comments clear this up!

This is closure :

Outer function function(window, google) {}(windows, google) used to create namespace, in that namespace (google and window passed there after init):

  • Mapster prototype description with passed namespace (google object)
  • After that object created and assigned as window property
  • So we have object wich will know about object. 对象,这将了解对象。 Outer round brackets needed to run that unnamed function immediately after definition.

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM