当前位置: 动力学知识库 > 问答 > 编程问答 >

having multiple instances of javascript objects

问题描述:

I've tried to look for a similar question and either can't phrase it properly or I'm being rather silly. I'm relatively new to JavaScript, and have a question about creating multiple object instances:

Here it is:

Say you're trying to build a 'list builder' dynamically with javascript. You create multiple lists and add items to them. So you build a class like so (note, the code is mostly illustrative to try and clarify the question):

var dynamicList = function(listName){

this.listTitle = listName;

}

dynamicList.prototype = {

buildList : function(){

var template = $('<ul id="'+ this.listTitle +'"></ul>').append('<h2>' + this.listTitle + '</h2>';

$(body).append(template);

}

}

now here comes the question:

Say I use an input form to create the list wrapper, and each time they submit the form, a new list is born. How is this managed? What I would presume would need to happen would be creating a new object each time:

var list1 = new dynamicList("[user input title from form]"); //first list

list1.buildList();

var list2 = new dynamicList("[user input title from form]"); //second list

list2.buildList();

var list3 = new dynamicList("[user input title from form]"); //third list

list3.buildList();

var list[n] ... // and so on

list[n].buildList();

But I can't figure out how to do this. Can I dynamically create variable names, or how would one approach this problem? Would you wrap it in a higher level object and create an increment system for each list created? Is this even a problem, or could you just recursively use var list = new dynamicList for each form?

I hope I have framed my issue in a way that everyone can understand, thanks for taking the time to read through it. I'd also appreciate any suggestions as to how to structure the code to ensure utmost scalability.

Thanks!

网友答案:

If you want to have n of something and be able to reference them - put them into an array.

var myLists = []; //Shorthand for new Array()

var list = new DynamicList("[user input title from form]"); //first list
list.buildList()
myLists.push(list);

list = new DynamicList("[user input title from form]"); //second list
list.buildList()
myLists.push(list);

You could also get rid of the buildList() call by creating a constructor.

分享给朋友:
您可能感兴趣的文章:
随机阅读: