Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript convention: How do you assign arguments to the parent scope

Tags:

javascript

var problemtest = function () {

    var parameters;

    return function (parameters) {
        parameters = parameters;
    }
}

var mysolutiontest = function () {

    var parameters;

    return function (parametersIn) {
        parameters = parametersIn;
    }
}

This is more of a JavaScript convention question.

Usually I have code similar to that on top. A function take arguments and assigns it to parent scope. However, I cannot use it as in problemtest, as the parameters that are arguments hide the parameters from problemtest.

In OO Programming we can use this, but in JavaScript I cannot use this, so I usually implement a solution similar to mysolutiontest. However, I am not fully satisfied with this solution. Is there a better way of doing this?

like image 962
mamu Avatar asked Feb 23 '12 00:02

mamu


2 Answers

If your functions need to share some properties, then assigning them to an object is an elegant and common pattern:

var object = {

    property: ['item'],

    methodOne: function() {
        console.log(this.property);
    },

    methodTwo: function() {
        console.log(this.property); 
    }

};

object.methodOne(); // ['item']
object.methodTwo(); // ['item']

For further information on how 'this' works within an object - http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

like image 113
Simon Smith Avatar answered Nov 11 '22 11:11

Simon Smith


I usually use _parameters as a convention. This stems from my Java past. This isn't isolated to your example or to Javascript. Any language that does not force you to qualify the variables of any enclosing scope would lead you to the same problem.

var mysolutiontest = function () {
  var _parameters;

  return function (parameters) {
    _parameters = parameters;
  }
}

I've also seen people use p_parameters to quality function argument names. This is not one of my favorites tho.

var mysolutiontest = function () {
  var parameters;

  return function (p_parameters) {
    parameters = p_parameters;
  }
}

My 2c.

like image 2
Lior Cohen Avatar answered Nov 11 '22 11:11

Lior Cohen