I wanted to ask about the pros cons of my the following OOP style. I write my JS classes in the following manner.
var MyClass = function() {
// private vars
var self = this,
_foo = 1,
_bar = "test";
// public vars
this.cool = true;
// private methods
var initialize = function(a, b) {
// initialize everything
};
var doSomething = function() {
var test = 34;
_foo = cool;
};
// public methods
this.startRequest = function() {
};
// call the constructor
initialize.apply(this, arguments);
};
var instance_1 = new MyClass();
var instance_2 = new MyClass("just", "testing");
Is this a good approach? Is there any drawback? I don't use inheritance, but would it work this way to achieve inheritance?
Thanks in advance.
I think it's a very good approach. Don't be ashamed of the 'no inheritance' issue. Most OOP isn't about inheritance. The most important aspects are the encapsulation and polymorphism, and you've got them.
It can be argued (well, i usually argue) that inheritance is only needed for static languages, where you have to somehow tell the compiler that these two types (classes) are related, that they have something in common (the common ancestor) so that it can allow polymorphism. With dynamic languages, OTOH, the compiler won't care, and the runtime environment will find the commonalities without any inheritance.
Another point: if you need some inheritance in some places (and it's great in some cases, like GUIs, for example), often you'll find that you can easily interoperate between your 'simple' objects/classes, and other more complex and heavier. IOW: don't try to find a framework that fills all your needs and use it for everything; instead use the one that you're more comfortable with at each moment, as long as it helps with the specific problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With