在我正在创建的对象的init函数中,我想创建另一个对象的新实例。
目前,我的初始化代码如下所示:
var myObj = {
getData: function(){
var instance = this;
// Display preloader gif
instance.selectors.preloader.fadeIn();
// Make call for appropriate data */
dataManager.feed.get( function(data){
for( var i = 0, len = data.feed.length; i < len; i++ ){
var template = '';
}
}, window, null, '' );
instance.displayVideos();
},
init: function(){
var instance = this;
// Create new DataManager object
var dataManager = new DataManager();
}
}
myObj.init();
我的问题是我收到错误告诉我DataManager没有定义,有人能解释我是如何引用这个对象的吗?
答案 0 :(得分:2)
看,你的代码可能是可以挽救的,但维护起来会很糟糕。因此,我建议您使用一个闭包,在最终曝光之前,您可以根据需要准备您的对象:
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
答案 1 :(得分:0)
应在调用init()方法之前定义DataManager对象。 我在你的代码中看到了另外一个问题()。 dataManager变量未在getData()函数中声明/赋值。在这种情况下使用对象级变量。试试这个:在init方法中 -
init:function(){
var instance = this; // Create new DataManager object this.dataManager = new DataManager(); }
并在getData()方法中使用
this.dataManager
而不是
DATAMANAGER