0

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.

Léa Gris
  • 17,497
  • 4
  • 32
  • 41
arjun
  • 3,514
  • 4
  • 27
  • 48
  • 3
    You're somewhat overthinking this. You assign to `StaticExample.staticProp`, so you can access `StaticExample.staticProp`. It's right there where you assigned it to. – deceze Jan 08 '20 at 13:06
  • Static variables refer to a variable that has been allocated "statically", which means it lasts for the entirety of the program. They contrast with automatic variable that are stack-allocated, and objects, which are stored in heap memory. These are not really terms that you encounter much in JavaScript programming because you don't manually mess with memory and how things are allocated or deallocated. Is this what you mean when you say static, or are you referring to a static property of a class, which can be called without instantiating a new instance from it? – Stephen M Irving Jan 08 '20 at 15:13

1 Answers1

3

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.

deceze
  • 510,633
  • 85
  • 743
  • 889