Skip to content Skip to sidebar Skip to footer

Property Added To A Js Object As A Prototype Is Hoisted, Whereas A Prototype Function Is Not

I am (or at least I thought I was) pretty much familiar with the concept of Hoisting in JavaScript. Consider the following statements: A function declaration will be hoisted along

Solution 1:

You are confusing variables and properties here. Variables are hoisted, properties are not.

In your example, Dan is a variable, mana is a property of Dan.

JavaScript handles undefined variables differently from undefined properties.

Variables are hoisted when they are declared, by splitting off the left hand side of the declaration. i.e. var Dan = new User("Danny"); is split into two statements, var Dan; Dan = new User("Danny");. the var Dan is then hoisted to the top of the function. but the assignment stays in place.

If your code contatined only Dan = new User("Danny");, you would receive a ReferenceError, because you would be trying to make an assignment to a variable that isn't declared. The declaration is missing, thus the variable was never hoisted.

Properties, on the other hand, operate differently. Property accessors return the result of a hash lookup on the parent object. In the case of Dan.mana, the parent object is defined, so no ReferenceError, but mana is not a property of Dan, so the hash lookup returns undefined. No hoisting has occurred, because there is no variable declaration.

Therefore, prototypes cannot be tied to hoisting, because they are strictly assignment operations. Even if the prototype is modified at the beginning of the function, it wouldn't be affected by hoisting, since hoisting only affects the declaration of the variable, not the assignment (which happens on the right side of the call).

Solution 2:

No, assignments (to prototype properties or other) are not hoisted.

The code

functionUser() { this.name = ""; … }
varDan = newUser("Danny");
console.log("Hey there " + Dan.name + "! You have " + Dan.mana + " remaining mana.");
User.prototype.mana = 100;

does not work, it will log Hey there ! You have undefined remaining mana..

Solution 3:

Accessing a property that is not defined on the object will give you undefined. There is no hoisting rule in play here.

  • Liz.mana will give you undefined.
  • Liz.uppercut will also give you undefined.
  • Liz.agility will also give you undefined.

Calling Liz.uppercut(Dan) throws the error because you are trying to call Liz.uppercut, which is undefined, as a function. That leads to the “undefined is not a function” error.

Post a Comment for "Property Added To A Js Object As A Prototype Is Hoisted, Whereas A Prototype Function Is Not"