14 May, 2014
0 Comments
1 category
Just a reminder, when using a Immediately-Invoked Function Expression (IIFE), you can create private, public, shared and instance variables:
<!DOCTYPE html> <html> <head> <title>Show public - private - shared and instance variables.</title> </head> <body> <script> var Greeter = (function () { var v1 = 10; // This is a private variable shared by all instances of Greeter. function Greeter(name) { this.name = name; this.v2 = 20; // This is a public instance variable. var v3 = 30; // This is a private instance variable, can only be
// accessed by the current Greeter instance. } Greeter.prototype.v4 = 40; // This is a public variable shared by all instances of Greeter. Greeter.prototype.increase = function () { v1 = v1 + 1; this.v2 = this.v2 + 1; }; Greeter.prototype.logState = function () { console.log(this.name + ".v1 [" + v1.toString() + "]" +
this.name + ".v2 [" + this.v2.toString() + "]."); }; return Greeter; })(); var greeter1 = new Greeter("greeter1"); var greeter2 = new Greeter("greeter2"); greeter1.logState(); // Logs: greeter1.v1 [10] greeter1.v2 [20]. greeter2.logState(); // Logs: greeter1.v1 [10] greeter1.v2 [20]. greeter1.increase(); greeter1.logState(); // Logs: greeter1.v1 [11] greeter1.v2 [21]. greeter2.logState(); // Logs: greeter1.v1 [11] greeter1.v2 [20]. </script> </body> </html>
Tags: Javascript
Category: Uncategorized