Search code examples
javascripthoistingexecutioncontext

Javascript hoisting - cant understand this


Trying to learn Js and cant understand why DOM element doesn't get the value:

var Car = function(loc) {
  var obj = Object.create(Car.prototype);
  obj.loc = loc;
  obj.move = move;
  return obj;
};

Car.prototype = {
    move : function() {
    this.loc++;
  }
};

var emy = Car(1);
emy.move();

document.getElementById("id").innerHTML = emy.loc;

So I create a class constructor and its prototype object, but the last line - document.getElementById("id").innerHTML = emy.loc; is not being executed (unless I put it in the top of the file). Why is that?

Snippet:

https://jsfiddle.net/awj6mf1b/


Solution

  • You haven't defined what move is:

    var Car = function(loc) {
      var obj = Object.create(Car.prototype);
      obj.loc = loc;
      obj.move = move;  // <<< Here
      return obj;
    };
    

    Giving the error:

    Uncaught ReferenceError: move is not defined
        at Car (VM52:51)
        at window.onload (VM52:61)
    

    You can fix this by just putting the function in your object during instatiation:

    var Car = function(loc) {
      var obj = Object.create(Car.prototype);
      obj.loc = loc;
      obj.move = function() {
        this.loc++;
      }
      return obj;
    };
    

    Or by correctly adding the function to the prototype:

    var Car = function(loc) {
      var obj = Object.create(Car.prototype);
      obj.loc = loc;
      // Removed move from here
      return obj;
    };
    
    // This adds move to the cars prototype
    Car.prototype.move = function() {
      this.loc++;
    }