dboots / javascriptoop

An example of OOP in Javascript
0 stars 0 forks source link

your static methods have public access #1

Open tobymackenzie opened 8 years ago

tobymackenzie commented 8 years ago

Just wanted to point out that prototypically inherited methods have full access to any instance's this and thus all public properties and methods of the instance or its prototypes. You could call this.GetFoo() from .StaticFoo() and it would return the _foo of that instance. .StaticFoo() doesn't have direct access to the private stuff though. There are memory advantages to having shared methods between all instances.

dboots commented 8 years ago

Hey Toby, thanks for the note! I looked into this and re-read your comment a few times. Let me make sure I got this right.

It seems like if my prototype methods were to be truly static, it would need to not have access to this.

On the flip side, Javascript's use of prototype seems to create a hybrid static/public method which can be either good or bad depending on the solution.

Thanks again for the feedback! I'm always trying to refine how to do things "right", especially in the wacky world of Javascript.

tobymackenzie commented 8 years ago

The prototype is really more of JS's inheritance mechanism. Any given prototype of an instance is somewhat like a parent / ancestor class of the instance. An instance of a subclass will have access to all methods on the prototype of its parent class, as well as on its own, where any properties / methods on the subclass prototype override the parent prototype's and any attached to the instance itself override those on the class's prototype chain. You can actually see this with an ObjA instance because all JS objects inherit from Object, and get some methods from it, like .hasOwnProperty(), which is on Object.prototype.

Statics more comparable to some other languages would probably be more like properties attached directly to the class (eg the function ObjA) itself. ObjA.StaticFoo = function(){}; would be callable like ObjA.StaticFoo(). this inside of that function would refer to ObjA itself. this.StaticFoo would be undefined inside of any of its instances' methods, unless you defined it separately. Comparing to Object again, this is like Object.keys(). There is no automatic inheritance of these static properties, so ObjA.keys() will be undefined unless you explicitly define it.