0

I want to create a function like this, but I want the variable name and colour to be properties of this function, which means I just have to give them value when construct the function and do not have to declare them each time I call the function.

function A(input) {
    var name = ["USA", "Japan", "India"]; // make it properties
    var color = ["blue", "red", "green"]; // make it properties
    var index = name.indexOf(input);
    return color[index];
}

To make it clear, let me show my ideal code like this:

function A(input) {
    var index = this.name.indexOf(input);
    return this.color[index];
}
A.name = ["USA", "Japan", "India"];
A.color = ["blue", "red", "green"];

Is it possible to set the function some properties like object? Thanks

Finally the problem is solved by module pattern, please attach to the accepted answer.

Summer Sun
  • 947
  • 13
  • 33

3 Answers3

2

A module pattern could do this, but it will make the properties private (I don't know if it's what you need):

var A = (function() {
    var name = ["USA", "Japan", "India"];
    var color = ["blue", "red", "green"];

    return function(input) {
        var index = name.indexOf(input);
        return color[index];
    };
})();
Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
0

The easiest way you can do this via passing the values in the parameter.

function A(input, name, color) {
    var index = name.indexOf(input);
    return color[index];
}
//Can be called like this
A("USA", ["USA", "Japan", "India"], ["blue", "red", "green"]);

Alternatively you can pass an object to a then just get from it.

function A(objectInput) {
  var input = objectInput.input ? objectInput.input : "",
      name =  objectInput.name  objectInput.name : [],
      color = objectInput.color ? objectInput.color : [],
      index = name.indexOf(input);
  return color[index];
}
//Called like this.
A({
   input: "USA",
   name:  ["USA", "Japan", "India"],
   color: ["blue", "red", "green"]
});
Nathan
  • 1,520
  • 1
  • 12
  • 21
0
function A(input) {
    var index = A.country.indexOf(input);
    return A.color[index];
}
A.country = ["USA", "Japan", "India"];
A.color = ["blue", "red", "green"];

console.log(A("USA")); //Blue

Don't use name as property name, it returns function name by default.

Better code style:

function A(input) {
    return A.colors[input];
}

A.colors = {
    "USA": "blue",
    "Japan": "red",
    "India": "green"
}
Maxx
  • 1,740
  • 10
  • 17