ほら、あなたのコードは救い出せるかもしれませんが、それを維持するのは地獄のようになるでしょう。したがって、最終的に公開する前に、オブジェクトを必要なだけ準備できるクロージャを使用することをお勧めします。
var myObj = (function(current)
{
'use strict';//<-- not necessary, but highly recommended
var instance = {};//<-- this is going to become the value myObj references
//if you want the init method, make a function object
var init = function()
{
instance.dataManager = new DataManager();
};
instance.init = init;//<-- make it "public"
//alternatively:
instance.dataManager = new DataManager();
//OR to have access to an instance of the DataManager object, but as a
// "private" property:
var dataManager = new DataManager();
//All methods or functions declared in this scope will have access to this object,
// the outer scope won't!
//same for getData, use either one of the following:
var getData = function()
{
//refer to the instance, not by using this, but use instance var
//which is safer, and immutable thanks to the closure we're building
};
instance.getData = getData;
//OR:
instance.getData = function()
{
//same function body, just created and assigned directly
};
//if you chose to use the init method:
instance.init();
//if you created an init function, but didn't assign it to the instance object:
init();
//when the instance object is all set up and good to go:
return instance;//will be assigned to the myObj variable
}(this));//call function and pass current scope as argument
次に、私が実際に取得できないコードは次のとおりです。
dataManager.feed.get( function(data)
{
//...
for( var i = 0, len = data.feed.length; i < len; i++ )
{//loop through an array of sorts
var template = '';//and initialize a variable to an empty string each time?
}
}, window, null, '' );
なんで?ポイントは何ですか、それともこれは単なるダミーループですか?
私の見方では、ここには2つの大きな問題があります。DataManager
1つ目は、コンストラクター関数を含めることができなかったことです。コンストラクターがコードで定義されていると仮定します。
var myObj = {
init: function()
{
var instance = this;
// Create new DataManager object
var dataManager = new DataManager();
},
myObj.init();//<== this can't work
};
オブジェクトリテラルのメソッドを、まだ定義している間に呼び出しています。それは機能しません:
var myObj = {
init: function()
{
var instance = this;
// Create new DataManager object
var dataManager = new DataManager();
}
};
myObj.init();//<== now myObj exists, and has an init method