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