0

For js, I have following function:

function custom(){
 var rhcmm_append = function (data) {       
    var id    =  data.ids;
    var name  =  data.names;
    // and more variables and conditions etc
 };
 ...
} 

I have few occasions in which I use the same variables and functions inside of function(data).

Is there a way to make these variables into a function that I can re-use?

For example:

 function VAR_FUNCTION(data){
    var rin_ids         =  data.thread_id.split(',');
    var rin_user        =  data.user_name;  
}

Thanks.

3
  • 1
    Can you explain more what you're looking for? Not sure I fully understand. Commented Feb 10, 2016 at 19:05
  • what exactly do you mean by re-use? you can simply assign new properties to an upper context variables from your VAR_FUNCTION Commented Feb 10, 2016 at 19:05
  • don't get it, what you are asking for. kind of default-values? Commented Feb 10, 2016 at 19:06

3 Answers 3

1

I didn't get exactly what you are asking for, however, I guess you would need something like this:

function extractor(data){
    // further processing might be done here.
    // processing on 'data'
    return {
        id: data.id,
        name: data.name
    };
}

Then you can use this utility function where ever you need.

function custom(){
    var rhcmm_append = function (data) {       
        var pairs  =  extractor(data);

        // do stuff with 'pairs'
    };
...
} 

Or

function VAR_FUNCTION(data){
    var pairs = extractor(data);
    // do stuff with 'pairs'
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can make these variables and functions global, limit their scope inside an anonymous function or use a global object that holds variables/functions, some examples:

// Global
var myVar = 'value';
function myFunction(){}



// Limit scope inside an anonymous function
(function(){
  var myVar = 'value';
  function myFunction(){}

  // To access variables/functions all your code needs to reside inside here
});



// Make a global object
var reusables = {
  myVar: 'value',
  myFunction: function(){}
};

// Example
reusables.myVar
reusables.myFunction();

Comments

0

If you want to re-use, you can create the global variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.