2015-07-02 37 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