Saturday, 28 May 2016

Static Methods in JavaScript

I wrote in the past that I found it confusing (in the JavaScript world) how some Object methods had been made static (Object.getOwnPropertyNames) and others made instance methods (Object.prototype.hasOwnProperty). I gave some reasons at the time, but I think I missed a pretty important one, probably cause in other languages it does not apply.

One main reason to do so, myClass.method(instanceOfMyClass) rather than instanceOfMyClass.method() is if we want to prevent overriding. One object could override the "inherited" method by directly setting it in itself, or somewhere else in the prototype chain. If you are using the "static" form, you can not override it for some selected objects, and if you set it as non writable, you can not override at all. When it is an instance method, you can set it as non writable to avoid changes to the original one, but that does not prevent it from getting added the overriden method somewhere down the prototype chain or directly in the instance.

In order to ensure that your code is calling the original instance method and not an override will drive people to write code like this:;
to avoid surprises in case someone has redefined hasOwnProperty in myObj.

In C# you just avoid the possibilities of overriding by not setting as virtual the method that you want to protect. Well, this is partially true, cause someone can hide the inherited method by declaring it as new. In that case, if you do the call through a variable declared of the base type you will for sure call the base method (irrespective of the real run time type, as the method resolution is done at compile time). If you use a variable of the derived class performing the hiding, the call (also set at compile time) will go to the "redefined" method in the derived one, skipping the hidden method. You can read more here

No comments:

Post a Comment