2011-03-15 2 views
0

私はJavascriptを初めて使用しているので、次のコードが良いかどうか疑問に思います。Javascriptのプロトタイプクラスリテラルのベストプラクティス

CustomClass = function(var1, var2) { 
    this.var1 = var1; 
    this.var2 = var2; 
}; 
CustomClass.prototype.aMethod = function() { 
    console.log("my class method"); 
}; 

// Intend as main .js object, if that makes sense 
var m = { 
    object1:CustomClass.prototype, 
    object2:CustomClass.prototype, 

    initObjects:function() { 
     m.object1 = new CustomClass(value1, value2); 
     m.object1.aMethod(); 
     m.object2 = new CustomClass(value1, value2); 
     m.object2.aMethod(); 
    } 
}; 

"s"リテラル内にカスタムクラスを作成する必要がありますか?

すべてのヘルプは非常にあなたの実際のコードにしたよう

答えて

0

を理解されるであろう。

// globally scoped. Only avoided with closures and hoisting as shown below 
// Also doesn't really make sense to define CustomClass on m unless you want 
// To use it directly instead of through a factory function 
CustomClass = function(var1, var2) { 
    this.var1 = var1; 
    this.var2 = var2; 
}; 
CustomClass.prototype.aMethod = function() { 
    console.log("my class method"); 
}; 

// Intend as main .js object, if that makes sense 
var m = { 
    // No reason to initialise them to the prototype. Doesn't really make sense 
    // m can be edited without needing to intialise object1 or object2 at all 
    object1:CustomClass.prototype, 
    object2:CustomClass.prototype, 

    initObjects:function() { 
     m.object1 = new CustomClass(value1, value2); 
     m.object1.aMethod(); 
     m.object2 = new CustomClass(value1, value2); 
     m.object2.aMethod(); 
    } 
}; 

より閉鎖や巻上に基づく使用であるかもしれない別のパターン。これはより機能的なアプローチをとり、標準的な古典的な継承から遠ざかります。もちろん

// Create closure to localise scope. 
(function() { 
    // global object to store anything that will be hoisted to global scope 
    var global = {}; 

    // Constructor that uses local objects and defines methods on 
    // this directly. 
    var CustomClass = function(_a,_b) { 
     var a = _a; 
     var b = _b; 

     this.method = function() { console.log("foo"); } 
    } 

    // init function will be hoisted to global scope. 
    global.init = function() { 
     global.object1 = new CustomClass(v1, v2); 
     object1.method(); 
     global.object2 = new CustomClass(v1, v2); 
     object2.method(); 
    } 

    // Hoist you global object into the global variable "m" on window. 
    window.m = global; 
}()); 

あなたはより多くのオブジェクト構成の代わりに、オブジェクトの継承を使用する必要があり、これはまた少しだけ遅くなるので、あなたはプロトタイプチェーンを失います。あなたの作成する1000以上のオブジェクトを作成する場合、スピードの損失は本当に顕著です

+0

私はあなたの答えにv1とv2が定義されていないことを恐れています。 –

関連する問題