2016-10-25 45 views
-1
export class MyClass { 
    myFuncA(msg){console.log('A: '+msg); console.log('this: ',this);} 

    myFuncB(msg){console.log('B: '+msg); console.log('this: ',this);} 
} 

我有一個名爲mc的類實例;我需要一種方法來執行一個Typescript類的動態命名函數。Typescript:如何爲動態執行的函數提供參數

此執行正常工作:

export class CallingClass { 
    constructor(){ 
     let mc = new MyClass(); 
     mc['myFuncA'].call(); // outputs 'A: undefined' 'this: undefined' 
    } 
} 

我有3個問題:

  1. 我怎樣才能提供論據? mc['myFuncA'].call('message')不起作用
  2. 如何將this設置爲CallingClassmc[...].call(...).bind(this)錯誤
  3. 如何將this設置爲MyClass

plunker

+2

讀取文檔:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call –

+0

@BryanChen謝謝布萊恩,這很有幫助。不知道爲什麼我認爲這會很複雜。你是否在意足夠寫一個解決方案,以便我可以選擇它?否則,我會寫我自己的。 – BeetleJuice

回答

1

請閱讀Function.prototype.call()

我如何提供參數的文檔? MC [ 'myFuncA'。電話( '信息')不工作

就像正常的函數調用

mc['myFuncA']('message') 

,或者如果你真的想用call

mc['myFuncA'].call(mc, 'message') 

我如何設置這是CallingClass? MC [...]調用(...)。結合(這)錯誤

它傳遞給call作爲第一個參數

mc['myFuncA'].call(this, 'message') 

這是你如何使用綁定

mc['myFuncA'].bind(this)('message') 

我怎樣才能設置這是MyClass?

mc['myFuncA'].call(mc, 'message') 

mc['myFuncA']('message') 
相關問題