[thelist] [javascript] object literal question

liorean liorean at gmail.com
Wed Mar 8 22:59:33 CST 2006


On 08/03/06, m.milicevic <me at machak.com> wrote:
> you could also use associative arrays

That's what an object literal is. All objects are in effect
associative arrays in JavaScript. There's no need to use an array if
you aren't taking advantage of the array specific methods and
behaviors, especially the dynamically changing length property.

On 08/03/06, Tom Dell'Aringa <pixelmech at yahoo.com> wrote:
> Or am I going about building this object the wrong way?

I would say so. It sounds to me like you want two different objects.
One list of priced products, and one object for each item in that
list.

    var
        productList=[];
    productList.createProduct=function(sName,nPrice,bToggle){
        var
            obj={
                name:sName,
                price:nPrice,
                toggle:bToggle};
        this.push(obj);
        return obj;};

    // Create product:
    var
        productWidge1=productList.createProduct('Widge 1',15.25,false);

    // Access it from that variable:
    doSomethingWithProduct(productWidge1);
    // Or access it from the array:
    doSomethingWithProduct(productList[0]);

    // Do something with all of them:
    for(var l=productList.length,i=0,i<l,i++)
        doSomethingWithProduct(productList[i]);

Or, if you don't want it in the form of an array, but instead as named
properties:

    var
        ProductList={
            createProduct:function(sName,nPrice,bToggle){
            return this[sName]={
                name:sName,
                price:nPrice,
                toggle:bToggle}}];

    // Create product:
    var
        productWidge1=productList.createProduct('Widge 1',15.25,false);

    // Access it from that variable:
    doSomethingWithProduct(productWidge1);
    // Or access it from the array:
    doSomethingWithProduct(productList['Widge 1']);

    // Do something with all of them:
    for(var i in productList)
        doSomethingWithProduct(productList[i]);
--
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the thelist mailing list