Menu

JavaScript and Static Methods

JavaScript and static methods are something special, they don't work as you expect it form an object oriented language. Take the following example:

function A () { }

// A "static" Method
A.nodeName = function () {
  alert("Name is A");
}

A.prototype.doSomething = function() {
  alert("doSomething");
}

A.nodeName();  // Works perfectly fine
var a = new A()
a.nodeName();  // Does not work at all

Why is the last statement not working as it should? The answer is easy, because JavaScript is a prototyped language. When invoking the constructor new A(), it copies all prototyped functions and variables to the new object a. An it's obvious, that A.nodeName is not part of the prototype, so it is not copied.

There are numerous ways to get around this. A rather nice workaround is to add the following snippet.

A.prototype.nodeName = function() {
  return this.__proto__.constructor.nodeName();
}

What does it do? Every object has a reference to it's original prototype __proto__. And the original prototype has a reference to the original constructor. Which has again a reference to his originating object. Which is equivalent to our object A which contains the "static" method. Thus we can use this and invoke our method nodeName().

Try it! the example above works now as it should. It even work with inheritance.

Posted by Thomas Schmid 2012-03-26 | Draft

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.