Is there a cleaner/nicer/quicker way to do this?
taskList = new Array();
currentTask = new Object();
closedTask = new Object();
search = new Object();
taskList.push(currentTask);
taskList.push(closedTask);
taskList.push(search);
Is there a cleaner/nicer/quicker way to do this?
taskList = new Array();
currentTask = new Object();
closedTask = new Object();
search = new Object();
taskList.push(currentTask);
taskList.push(closedTask);
taskList.push(search);
Yeah, if you're not using currentTask, closedTask and search anywhere else you can do:
var taskList = [ {}, {}, {} ];
Otherwise:
var currentTask = {},
closedTask = {},
search = {};
var taskList = [ currentTask, closedTask, search];
tasklist is not a property in the global scope.Both of these methods work, depending on what you are trying to accomplish.
var taskList = [{}, {}, {}] //Creates 3 Objects
OR
var taskList = [new Object(), new Object(), new Object()] //Object() can be replaced with any other object such as Array, String, etc
You can then just access the individual objects using:
taskList[x]; //Where x is the index of the object.
An even nerdier variant :
var currentTask,
closedTask,
search,
taskList = [currentTask={}, closedTask={}, search={}];
Joke aside, using the initializers syntax,
{} is basically equivalent to new Object and [] to new Array.
The braces syntax allows to create untyped objects (i.e. objects of the generic Object class), while the new operator allows to create class instances.
If you want to create an empty, untyped object, the result is equivalent.
Now consider this:
var Dog = function (value)
{
this.bone= value;
}
Dog.prototype.bark = function () { console.log ("Woof!"); }
var Alf = new Dog (10); // Alf is a true able dog
var Rex = { bone:10 }; // Rex is just a generic object aping a dog
console.log (Alf.bone); // 10
console.log (Rex.bone); // 10
Alf.bark(); // Woof!
Rex.bark(); // generic objects don't bark !
new Object(), new Array() or just the brackets/curly brackets?{} or [] initializer is not gramatically the same thing as the invokation of the new operator, but yes, for all practical purposes it is.new object() and {} are both initializers with a different syntax :). See my edit