Another Javascript Class Study
by Neviton
JavaScript
var NS = NS || {};
NS.ObjA = function() {
'use strict';
var _var = 'test 1'; // static private member (can't be accessed by prototypes without a closure: http://stackoverflow.com/questions/483213/javascript-private-member-on-prototype)
this._this = 'test 2'; // public member not shared
function write() {
}
};
// Prototype provides method sharing, avoiding duplication over class instances
NS.ObjA.prototype = {
print: function() {
'use strict';
try {
console.log(this._var);
console.log(this._this);
} catch(e) {}
}
}
var objA1 = new NS.ObjA();
var objA2 = new NS.ObjA();
objA1.print();
objA2.print();
console.log(objA1.print === objA2.print);
NS.ObjB = (function() {
'use strict';
function write() {
console.log('write');
console.log(this.text);
}
var ObjB = function(text) {
this.text = text;
}
ObjB.prototype = {
print: function() {
write.call(this);
}
}
return ObjB;
}());
var objB1 = new NS.ObjB('Lorem');
objB1.print();