I’m wondering how could you initialize a variable by passing it as a reference on a function. Here is the code:
var carToy, trainToy;
function setToyValue(name, description, toy) {
toy = new makeToy(name, description);
}
function makeToy(name, description) {
this.name = name;
this.description = description;
}
function start() {
setToyValue("toy car", "red, 4 wheels", carToy);
setToyValue("train car", "green, with 5 wagons", trainToy);
console.log(carToy);
console.log(trainToy);
}
start();
Obviously, at the end, carToy and trainToy still are undefined… Any suggestions on how to do it? Here is the fiddle –> http://jsfiddle.net/Osoascam/8YMsz/
JavaScript acts this pass by reference differently (somewhat). Basically everything is passed by value in JavaScript. If you pass an object to a function and change some property in you and you have access to those changed values outside that function, that makes us guess that it’s passed by reference, but actually for objects the value of the variable is a reference.
You can’t actually achieve this using JavaScript but there’s simple workarounds you can follow. If you know that every object in JavaScript is a flavor of Dictionary of Key Value pair, and all variables can be accessed by indexers.
In your case, as i said the value of the variable is a reference and its pointless to change the value where it wouldn’t persist. And you also know that your current context (
this) is theglobalso you may access your variable through indexer and change the value by name.The only difference is, you are passing the name of the function as string.
That’s the best you can do in my opinion.