Below are two code snippets - one in Go and the other in JavaScript - essentially doing the same thing.
// Go
package main
import "fmt"
type Engine struct {
bootTimeInSecs int
}
func (e *Engine) Start() {
fmt.Printf("Engine starting in %s seconds ...", e.bootTimeInSecs)
}
type Start func()
type BenchmarkSuite struct {
workloads []string
start Start
}
func main() {
engine := Engine{10}
benchmarkSuite := BenchmarkSuite{workloads: []string{}, start: engine.Start}
benchmarkSuite.start()
}
Output
Engine starting in 10 seconds ...
// JavaScript
function Engine(bootTimeInSecs) {
this.bootTimeInSecs = bootTimeInSecs
}
Engine.prototype.constructor = Engine
Engine.prototype.Start = function() {
console.log("Engine starting in " + this.bootTimeInSecs + " seconds ...")
}
function BenchmarkSuite(workloads, start) {
this.workloads = workloads
this.start = start
}
BenchmarkSuite.prototype.constructor = BenchmarkSuite
engine = new Engine(10)
benchmarkSuite = new BenchmarkSuite([], engine.Start)
benchmarkSuite.start()
Output
Engine starting in undefined seconds ...
I know the workaround in JavaScript, but that's not the question. Why did JavaScript decide not to retain the original execution context of a function?