Javascript Basics for OOP
Related Javascript language features:
* Object.this
* Function.prototype
* Function.apply(func,[args])
A Class Template:
1, Class Factory
var Factory = function(C) { var F = typeof C.c === "function" ? C.c : function() {}; F.prototype = C; return F; };
2, Class Constructor
var Class = Factory({ a: null, c: function(a) { this.a = (a) ? a : 0; }, d: function() { return this.a; } }); var obj = new Class(1); alert(obj.d());
3, Class Inheritence
var Factory = function(C, P) { var F = null; if (arguments.length == 1) { F = typeof C.c === "function" ? C.c : function() {}; F.prototype = C; } else if (arguments.length == 2) { F = typeof C.c === "function" ? C.c : function() { P.apply(this, arguments); }; F.prototype = C; for (var property in P.prototype) { F.prototype[property] = P.prototype[property]; } } return F; }; var Class1 = new Factory({ a: null, c: function(a) { this.a = (a) ? a : 0; }, d: function() { return this.a; } }); var Class2 = new Factory({ b: null, c: function(a, b) { Class1.prototype.c.apply(this, arguments); this.b = (b) ? b : 0; }, e: function() { return this.a + this.b; } }, Class1); var obj1 = new Class1(1); var obj2 = new Class2(2, 3); alert(obj.d()); alert(obj2.e());
That's all.