Search code examples
javascriptfunctionobject-literal

Javascript, can I pass a reference to a current object to function within an object literal definition?


Good Morning,

I have a function that takes an options hash as it's parameter, can I call that function inside an object literal definition? Like this

 function dataCallback(opts) {

    var rowSelector = opts['id'] + ' .gridContent';
    var liSelector = opts['id'] + ' li';

    return function(args) { //do something with opts... 
              return; 
    }
    //omitted...

} 

var obj = { x : {id = '#someId1', callback: dataCallback(//what can I pass here? this? x? obj.x? nothing seems to work...)}
           , y : {id = '#someId2', callback: dataCallback(///???, this? y? obj.y?)}  };

I hope my question makes sense. Perhaps I worded it incorrectly in the title. Anyways, if someone can straighten me out here I would truly appreciate it. Thanks for any tips or tricks.

Cheers,
~ck in San Diego


Solution

  • From what I understood is that you want to assign the return value of the function to a property of the object and passing the object itself to the function. Is this correct?

    You cannot do this in one go. You have to separate the steps:

    var obj = {
        x: {id: '#someId1'},
        y: {id: '#someId2'}
    }; 
    
    obj.x.callback = dataCallback(obj.x);
    obj.y.callback = dataCallback(obj.y);