gpt4 book ai didi

javascript - 使用另一个对象的 init 函数创建新对象

转载 作者:行者123 更新时间:2023-12-02 19:18:47 25 4
gpt4 key购买 nike

在我正在创建的对象的 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 未定义,任何人都可以解释我如何引用该对象吗?

最佳答案

看,你的代码可能是可以挽救的,但维护起来会很糟糕。因此,我建议您使用闭包,在最终公开对象之前,您可以根据需要准备对象:

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

关于javascript - 使用另一个对象的 init 函数创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12779507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com