Reputation: 1382
I have one here:
What I noticed is that in this framework, all variables are static ( they are on the prototype chain ), and are only "instance" based if you set them in the constructor.
I'm using these terms from CS101 usually taught via Java.
Is there a better way to do this?
By default I set instance variables to a string 'instance' which will be replaced once the constructor is called.
var klass = function (obj, config_module) {
if (config_module === 'constructor') {
var object_public;
if (obj.constructor) {
object_public = obj.constructor;
delete obj.constructor;
}
_.some(obj, function (val, key) {
object_public.prototype[key] = val;
});
return object_public;
}
};
var Test = klass({
// instance, set in constructor
A : 'instance',
// static, not set in constructor
B : 4,
constructor: function (some_var) {
this.A = some_var;
},
get: function () {
return 2;
},
set: function () {
}
}, 'constructor');
var instanceA = new Test('A');
var instanceB = new Test('B');
console.log('Start');
console.log(instanceA.A);
console.log(instanceB.A);
Upvotes: 0
Views: 47
Reputation: 12035
Give MooTools a try. It is as close as it can get without the use of other languages which compile to JavaScript (like CoffeScript or TypeScript).
Here is an example MooTools class:
Foo = new Class({
// instance variable:
name: '',
// construtor:
initialize: function(name) {
this._setName(name);
},
// instance method:
getName: function(){
return this.name;
},
// protected instance method:
_setName: function(name) {
this.name = name;
}.protect()
});
// static variable:
Foo.bar = 'bar';
// static method
Foo.bar = function(){}
// instance object:
var myFoo = new Foo('my new name');
var theName = myFoo.getName();
var checkInstance = instanceOf(myFoo, Foo);
Upvotes: 1