4

以下の構成を使用すると、プライベート変数、パブリックおよびプライベート関数を持つことができます。では、なぜ名前空間を作成するためのさまざまな方法がすべてあるのでしょうか。

名前空間は、関連する動作とスコープを持つ関数とは根本的に異なりますか?

グローバル名前空間、たとえばブラウザのウィンドウオブジェクトを、作成する関数が多すぎることで汚染しないという点がわかりますが、それは以下でも実現できます。

基本的なポイントが欠けているようです。

// Constructor for customObject  
function customObject(aArg, bArg, cArg)  
{  
    // Instance variables are defined by this  
    this.a = aArg;  
    this.b = bArg;  
    this.c = cArg;  
}  

// private instance function  
customObject.prototype.instanceFunctionAddAll = function()  
{  
    return (this.a + this.b + this.c);  
}  

/*  
  Create a "static" function for customObject.  
  This can be called like so : customObject.staticFunction  
*/  
customObject.staticFunction = function()  
{  
    console.log("Called a static function");  
}  

// Test customObject  
var test = new customObject(10, 20, 30);  
var retVal = test.instanceFunctionAddAll();  
customObject.staticFunction();  
4

1 に答える 1

4

重要なのは、複数の関数があるかもしれないが、グローバルスコープを単一の変数(「名前空間」)で汚染したいだけだということです。

// Wrap in a immediately-executing anonymous function to avoid polluting
// the global namespace unless we explicitly set properties of window.
(function () {
    function CustomObject(/*...*/) { /*...*/ } 
    // Add methods, static methods, etc. for CustomObject.

    function CustomObject2(/*...*/) { /*...*/ } 
    // Add methods, static methods, etc. for CustomObject2.

    var CONSTANT_KINDA = "JavaScript doesn't really have constants";

    // Create a namespace, explicitly polluting the global scope,
    // that allows access to all our variables local to this anonymous function
    window.namespace = {
        CustomObject: CustomObject,
        CustomObject2: CustomObject2,
        CONSTANT_KINDA: CONSTANT_KINDA
    };
}());

また、Felixは正しいです、あなたの「プライベート」インスタンス関数は実際には非常に公開されています。実際のプライベートメソッドが必要な場合は、Crockfordの「JavaScriptのプライベートメンバー」を参照してください。

于 2011-07-08T20:28:00.000 に答える