[英]Can I use classes with the javascript module pattern?
我有一堆“模塊”,它們遵循這篇熱門文章中所述的“ JavaScript模塊模式” 。 據我了解,這些模塊是一種將各種行為匯總到整潔的名稱空間中的方法。
但是,如果我希望能夠創建一個接受參數的唯一對象實例怎么辦? 就目前而言,我無法做到這一點,因為所有數據都是共享/靜態的。 我希望能夠這樣做:
var foo = new Some.Namespace.Whatever.Foo(config);
我們已經使用了一段時間,因此無法更改模式的結構,並且效果很好。 我只想對其進行調整,以便可以將一些“類”放入其中,以處理非靜態數據。
為什么不嘗試這個?
var MODULE = (function () {
var my = {};
my.SomeClass = SomeClass;
function SomeClass(six) {
this.six = six;
}
SomeClass.prototype.five = 5;
return my;
})();
當您調用var obj = new MODULE.SomeClass(6)
,它將為您提供一個新對象。 obj.five
在SomeClass
所有實例之間共享,因為它附加到原型。 但是, obj.six
特定於該實例,因為它附加到obj
。
或者,您可能不需要將您的班級置於模塊內。 您可以在適當的地方使用一個類來替換模塊,因為在這種情況下,模塊和類都具有某些重疊的功能。
這可能是模塊模式的過度使用,但這是您的意思嗎?:
var Some = (function() {
var util = { /* ... */ };
return {
Namespace: (function() {
return {
Whatever: (function() {
var Foo = function(config) {
this.foo = config.foo || "foo";
this.bar = config.bar || "bar";
};
var Bar = function() {};
Foo.prototype.toString = function() {
return this.foo + " " + this.bar;
};
return {
Foo: Foo,
Bar: Bar
}
}())
};
}())
};
}());
var foo = new Some.Namespace.Whatever.Foo({foo: "hello", bar: "world"});
foo.toString() // "hello world"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.