Declare a variable with the same name as the function, but with a lower case!
this
In JavaScript you use the keyword this to reference to the parent object.
funcion Car(model) { this.model = model; this.plateNr = generatePlateNr(); }
In the code above, this refers to the function object Car.
But what happens if you have objects within objects?
funcion Car(model) { this.model = model; this.plateNr = generatePlateNr(); function generatePlateNr() { if(this.model == "ford") { return "ABC"; } else { return "DEF"; } } }
this.model and this.plateNr points to the Car function properties. But this.model in function generatePlateNr points to the generatePlateNr function!
So how do you refer to the Car function inside the generatePlateNr function!?
funcion Car(model) { var car = this; car.model = model; car.plateNr = generatePlateNr(); function generatePlateNr() { if(car.model == "ford") { return "ABC"; } else { return "DEF"; } } }
You simply declare a variable with the same name as the function, but with a lower case!
That will give you some advantages:
- Easier to read the code
- Easier to replace variables
- Easier to understand the context
Written by Johan Zetterberg May 19th 2015.