Tag Archives: Singleton
A simple JavaScript singleton pattern
There are a number of different approaches that can be taken to creating singleton patterns in JavaScript – this one is both simple and effective and supports lazy initialisation. The following code shows typical usage of constructor functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function Vehicle() { // #1 this.objectString = "I am a vehicle"; this.serialNo = 0; } function Car() { // #3 return new Vehicle(); } var vehicle1 = new Vehicle(); // #2 vehicle1.serialNo = 1; var vehicle2 = new Vehicle(); vehicle2.serialNo = 2; var car = new Car(); // #4 console.log("vehicle1:"); // #5 console.log(vehicle1); console.log("\n\nvehicle2:"); console.log(vehicle2); console.log("\n\ncar:"); console.log(car); |
#1: … Continue reading
Posted in Application Development, JavaScript
Tagged constructors, function properties, Javascript, patterns, Singleton
Leave a comment