簡體   English   中英

Javascript模塊模式/原型模式:無法找出此代碼

[英]Javascript Module Pattern / Prototype Pattern : can't figure out 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);

希望這些評論能解決這個問題!

這是關閉

外部函數function(window,google){}(windows,google),用於創建名稱空間,該名稱空間(在初始化后傳遞給Google和窗口的名稱空間):

  • 具有傳遞的名稱空間的Mapster原型說明(Google對象)
  • 創建該對象並將其分配為window屬性之后
  • 所以我們有window.Mapster對象,這將了解google對象。 定義后立即需要外部圓括號來運行該未命名函數。

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM