Question

Answers like this one indicate that, when a JavaScript file is read, function declarations are loaded into memory during a first pass, and expressions are evaluated in a subsequent pass. However, the example below shows that functions inside a function are compiled after code is executed.

To get the code below to work, I must move the Child constructor outside the test function or place it before the call to new Child() if it is to remain inside the test function. In its current position, you will get a TypeError: this.init is not a method when you run the code.

Where can I find detailed information on when function declarations s within functions are evaluated?

document.addEventListener('DOMContentLoaded', function() {
  test()
}, false)


function test() {
  // Child declaration can go here

  var child = new Child()

  // If Child is placed here, this.init is undefined
  function Child() {
    this.init()
  }
  Child.prototype = new Ancestor(Child)
}


function Ancestor(constructor) {
  this.constructor = constructor
}
Ancestor.prototype.init = function init() {
  console.log(this)
}

// Child declaration can go here
Was it helpful?

Solution

The problem is that the init method comes from the Ancestor class. And you are inherit it after the creation of the child instance. For example the code below works.

setTimeout(function() {
    test()
}, 200);

function test() {
  // Child declaration can go here

  Child.prototype = new Ancestor(Child);
  var child = new Child();  

  // If Child is placed here, this.init is undefined
  function Child() {
    this.init()
  }

}

function Ancestor(constructor) {
  this.constructor = constructor
}
Ancestor.prototype.init = function init() {
  console.log(this)
}

So, just move the Child.prototype = new Ancestor(Child) above the calling of new Child. You don't need to put the Child constructor outside the test function.

In other words, in your example, init method is still not attached to the Child prototype when you call new Child.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top