2015-04-22 43 views
1

問題防止丟失作爲參數

傳遞如何防止環境的損失this變量作爲參數傳遞的函數裏面?

簡單的例子,也JSFiddle

var a = { 
    start: function() { 
     b.start(this.process); 
    }, 

    process: function(justAParameter) { 
     justAParameter += ' of multiple contexts!' 

     this.finish(justAParameter); 
    }, 

    finish: function(finishParameter) { 
     console.log(finishParameter); 
    } 
} 

var b = { 
    start: function(justAFunction) { 
     justAFunction('Hello world') 
    } 
} 

a.start(); 

期望輸出

Hello world of multiple contexts!

接收的輸出

TypeError: this.finish is not a function

回答

3

可以使用bindthisprocess()方法的值綁定時,它作爲一個參數

start: function() { 
    b.start(this.process.bind(this)); 
}, 

FIDDLE

引用真實