简体   繁体   中英

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

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);

try 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: function(){dataCallback(this)}
    }, y: {
        id: '#someId2',
        callback: function(){dataCallback(this)}
    }
};

obj.x.callback();

in order to do dataCallback(this) you need to put it in an anon fn or else this does not refer to the object, it refers to the global DOMWindow

Yes, nothing works, because JSON is not self-referenceable, only Firefox now supports Sharp Variable in JSON so that you may write like this:

function dataCallback(opts) {
    // your logic here
    return function(args) { /* logic here */ };
}

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

Note that Sharp Variable is only supported by some versoin of Firefox and will possibily be removed at future point, so use it at consideration. Syntax in Sharp Variable is extremely strict so that you should write "x:#1={" without any extra space in each character.

For reference of Sharp Variable: https://developer.mozilla.org/en/Sharp_variables_in_JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM