2017-01-12 29 views
-3

下面是兩個代碼片段 - 一個在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決定不保留保留原始函數的執行上下文?

+0

誰給了一個'close'表決的問題,可以你解釋這個問題將如何吸引**意見**基礎的答案? –

+0

請檢查答案,你忘了綁定功能 –

回答

1

在javascript中,當您將對象傳遞給BenchmarkSuite的構造函數時,函數不會綁定到對象engine

您必須將對象顯式綁定到該函數。 這是你必須做的

benchmarkSuite = new BenchmarkSuite([], engine.Start.bind(engine)) 

最簡單的使用綁定的()是什麼使一個,不管它怎麼叫,被稱爲與特定該值的功能。新的JavaScript程序員常犯的一個錯誤是從對象中提取一個方法,然後調用該函數並期望它將原始對象用作它(例如,通過在基於回調的代碼中使用該方法)。然而,如果不特別注意,原始物體通常會丟失。從創建功能的約束功能,使用原來的對象,巧妙地解決了這個問題

你可以參考here更多

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.bind(engine)) 
 
benchmarkSuite.start()

+0

@ bharat-khatri請檢查並提示答案,如果它幫助你:D –