· 7 years ago · Sep 11, 2018, 04:54 PM
1Static variables with John Resig's simple class pattern?
2function makeClass() {
3 return function _class() {
4 if(this instanceof _class) {
5 if(typeof this.init === 'function') {
6 this.init.apply(this, arguments);
7 }
8 } else {
9 throw new Error('Constructor called as a function');
10 }
11 };
12}
13
14var MyClass = makeClass();
15
16MyClass.prototype = {
17 init: function(width, height) { ... },
18 clear: function(ctx) {... },
19 draw: function(ctx) { ... }
20}
21
22MyClass.myVariable = 42;
23
24MyClass.prototype.xxx: 3, // ...
25var t1 = new MyClass();
26console.log(t1.xxx); // 3
27
28var t2 = new MyClass();
29t2.xxx = 5;
30console.log(t1.xxx); // still 3 :(
31
32MyClass.xxx = 3;
33
34init: function() {
35 var xxx = 3;
36 MyClass.prototype.getXXX = function() {
37 return xxx;
38 };
39 MyClass.prototype.setXXX = function(newXXX) {
40 xxx = newXXX;
41 }
42 }
43
44var t1 = new MyClass();
45 var t2 = new MyClass();
46 console.log(t1.getXXX()); // 3
47 console.log(t2.getXXX()); // 3
48 t1.setXXX(5);
49 console.log(t1.getXXX()); // 5 now
50 console.log(t2.getXXX()); // 5 as well, behold the power of closures!
51
52var statics = (function() {
53 var map = new WeakMap;
54 return function(inst) {
55 var ctor = inst.constructor;
56 return map.get(ctor) || map.set(ctor, {});
57 };
58})();
59
60var a = function() {};
61var b = function() {};
62
63var inst1 = new a;
64var inst2 = new a;
65var inst3 = new b;
66
67statics(inst1).foo = 123;
68statics(inst3).foo = 456;
69
70console.log( statics(inst1).foo ); // 123
71console.log( statics(inst2).foo ); // 123
72console.log( statics(inst3).foo ); // 456