0

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));
Salmen Bejaoui
  • 865
  • 1
  • 8
  • 22
  • More on constructor functions and prototype here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 I think IIFE and closures are already covered in the answers – HMR Oct 13 '14 at 10:37

2 Answers2

2
// 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!

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
1

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 window.Mapster object wich will know about google object. Outer round brackets needed to run that unnamed function immediately after definition.

    Michael Plakhov
    • 2,292
    • 2
    • 19
    • 21