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.

2
  • stackoverflow.com/a/2653364/2134604 Commented Aug 12, 2015 at 6:57
  • i can set properties for an object, but how can i call it as a function than? Commented Aug 12, 2015 at 7:08

3 Answers 3

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];
    };
})();
Sign up to request clarification or add additional context in comments.

Comments

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"]
});

1 Comment

thanks but i am not passing extra parameters here due to the requirement.
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"
}

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.