2015-07-02 40 views
-3

我覺得我在打字時會傳遞錯誤的函數。 我總是寫出來是這樣的:Typescript箭頭符號笨拙,另類?

var somefunc = (p1, p2, p3, p4) => { thatfunc(p1,p2,p3,p4) }; 

凡在普通的JavaScript我只想做:

var somefunc = thatfunc; 

更長的參數名稱這變得如此令人難以置信的笨拙和長長的寫,所以我在想,如果有一個更好的選擇。

實施例:

class A { 
    public foo = "bar"; 

    public thatfunc(x, y, z) { 
    console.log(this.foo); 
    } 
} 

class B { 
    var somefunc; 
    var a; 
    constructor() { 
    this.a = new A(); 
    this.somefunc = this.a.thatfunc 
    } 
} 

var b = new B(); 
b.somefunc("x", "y", "z") //will error undefined foo 

class B { 
    var somefunc; 
    var a; 
    constructor() { 
    this.a = new A(); 
    this.somefunc = (x, y ,z) => { this.a.thatfunc(x,y,z) } 
    } 
} 

var b = new B(); 
b.somefunc("x", "y", "z") // will work displays "bar" 
+4

當然,你可以做到這一點簡單的賦值在打字稿了。 – Pointy

+3

TypeScript只是「註釋的JS」。您仍然可以在TypeScript中編寫「純JS」。 – Joseph

+0

@Pointy我知道,但後來我不斷收到未定義的錯誤 – xDreamCoding

回答

2

this.somefunc = this.a.thatfunc

只需:

this.somefunc = this.a.thatfunc.bind(this.a); 

或者:

public thatfunc = (x, y, z) => { 
    console.log(this.foo); 
} 

凡在普通的JavaScript我只想做:

事實並非如此。在這種情況下,TypeScript JavaScript。

+1

謝謝!正在尋找替代符號,現在我可以愉快地:somefunc = thatfunc; – xDreamCoding

+0

高興。另外:https://www.youtube.com/watch?v = tvocUcbCupA – basarat