JSFiddle - React, Tailwind, and code Playground
JavaScript
//Predefined json from an external file.
var cat = {
"name": "cat",
"sounds": ["hiss", "meow"]
}
var dog = {
"name": "dog",
"sounds": ["bark", "growl"]
}
//I create an animal with several methods.
//Yeah, doing something like myAnimal.say = function(soundIndex) or something similar would probably be better here.
//But let's assume for some reason you haven't done that or can't.
function AnimalFactory(_json) {
var myAnimal = {}; myAnimal.name = _json.name;
for(var s in _json.sounds){
myAnimal["say"+_json.sounds[s]] = function(){
//What we want here is to make a function where 's' always refers back to the value 's' was when the function was created,
//and not to the 's' variable itself which will change as soon as we finish making the function.
console.log(_json.sounds[s]);
}
}
return myAnimal;
}
var myCat = AnimalFactory(cat);
//Function is created normally, but is still referencing the local 's' variable, which has long since changed to '1' instead of 0.
myCat.sayhiss(); //logs meow instead of hiss.
// Perhaps something like this:
function ImprovedAnimalFactory(animal) {
var myAnimal = { name: animal.name };
var makeSayFunction = function (sound) {
return function () { console.log(sound); };
};
for (var s in animal.sounds) {
myAnimal["say" + animal.sounds[s]] = makeSayFunction(animal.sounds[s]);
}
return myAnimal;
};
var improvedCat = ImprovedAnimalFactory(cat);
improvedCat.sayhiss();