簡體   English   中英

具有命名空間的JavaScript對象中的本地函數

[英]Local function in JavaScript object with namespace

我想創建一個命名空間來組織我的所有JavaScript。 我無法使用下面的代碼示例來創建一個方法來創建一個本地函數,以便除了在此Object中之外不能調用它。

window.JD = window.JD || {};

JD.Guid = {

    newGuid : function() {
        return JD.Guid.s4(); // Would like this to be this.s4();
    },

    s4 : function() {
        return Math.floor((1 + Math.random()) * 0x10000);
    }
}

我已經嘗試過使用JD.Guid = function() {...}但這也不起作用。 控制台告訴我該函數未定義。

我希望能夠從我的網站的任何地方調用JD.Guid.newGuid()

我想你在詢問module設計模式,在這種情況下你的代碼必須如下:

window.JD = window.JD || {};
JD.Guid = (function () {
    // This function is private,
    // you can re-use it only from public accessible method.
    var privateMethod = function() {
        return 'private';
    };
    return {
        newGuid : function() {
            return JD.Guid.s4();
        },
        newGuidThroughtThis : function() {
            return this.s4();
        },
        privateMethod: function() {
            return privateMethod();
        },
        s4 : function() {
            return Math.floor((1 + Math.random()) * 0x10000);
        }
    }
})();

現在您可以重復使用您的模塊並執行以下操作:

console.log(JD.Guid.s4());
console.log(JD.Guid.newGuid());
console.log(JD.Guid.newGuidThroughtThis());

作為輸出你會得到類似的東西:118723

我不確定我是否正在關注。 但是,您可以通過創建在函數中包裝代碼的上下文來創建無法在全局命名空間中訪問的本地函數:

(function() {
  window.JD = window.JD || {};

  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000);
  }

  JD.Guid = {
    newGuid: function() {
      return s4();
    }
  }
})();

我通常做這樣的事情:

var JD = (function(GLOBAL_JD){
      if(GLOBAL_JD === undefined) {
        var jd = {
          GUID: {
            newGuid: newGuid          
          }
        };

        return jd;
      }

  function newGuid() {
    return s4(); // Would like this to be this.s4();
  }

  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000);
  }
})(JD);

console.log(JD.GUID.newGuid());

http://jsbin.com/jodifeb/edit?js,console,output

暫無
暫無

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

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