Search code examples
javascriptinternals

Working of static variables in JavaScript


A bit of confusion on how static works in javascript.

function StaticExample() {}

StaticExample.staticProp = "Hello"

console.log(StaticExample.staticProp) // "Hello"

Here I have created a function and then created a static variable staticProp (not if we can call it static though). This adds the field staticProp to the constructor field on StaticExample's prototype

Question 1: Is there a specific reason to this behaviour(field getting added to the constructor property)?

Now the constructor is rewritten as below.

StaticExample.prototype.constructor = {}

console.log(StaticExample.staticProp) // "Hello"

Even after that, when I tried to access StaticExample.staticProp, it provides the correct value of Hello

Question 2: From where the staticProp fetched, even when the constructor where it was initially added is overwritten.


Solution

  • StaticExample is an object. A function object, but an object nonetheless.
    You assign a new property to it: StaticExample.staticProp = "Hello".

    StaticExample also happens to have a property prototype.
    The property StaticExample.prototype.constructor points to StaticExample.

    Now, you can obviously access StaticExample.staticProp, because it's simply a property of an object that you assigned.

    You can also replace the value of StaticExample.prototype.constructor with something else; now StaticExample.prototype.constructor doesn't point to StaticExample anymore. But StaticExample is still StaticExample and it still has the property staticProp that you created on it. You didn't replace the StaticExample object in any way. What you did replace was StaticExample.prototype.constructor, which is a different property of a different object.