下面是兩個代碼片段 - 一個在Go中,另一個在JavaScript中 - 實質上是做同樣的事情。Go vs JavaScript中執行方法的執行上下文
// 轉到
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()
}
輸出
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()
出把
Engine starting in undefined seconds ...
我知道JavaScript的解決方法,但這不是問題。爲什麼JavaScript決定不保留保留原始函數的執行上下文?
誰給了一個'close'表決的問題,可以你解釋這個問題將如何吸引**意見**基礎的答案? –
請檢查答案,你忘了綁定功能 –