看,你的代码可能是可以挽救的,但维护起来会很糟糕。因此,我建议您使用闭包,您可以在其中尽可能多地准备对象,然后最终公开它:
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, '' );
为什么?有什么意义,或者这只是一个虚拟循环?
在我看来,这里有两个主要问题。第一个是你没有包含DataManager
构造函数。假设在您的代码中定义了构造函数:
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