问题
As shown in this example, the assignment to a
and defining b
results in different function type.
export module A {
export class Test {
constructor(){}
a =(x) => { return Math.sin(x); }
b (x) : any { return Math.sin(x); }
}
}
this results in following js
var Test = (function () {
function Test() {
this.a = function (x) {
return Math.sin(x);
};
}
Test.prototype.b = function (x) {
return Math.sin(x);
};
return Test;
})();
but, I am bit confused about the spec 4.9.2 Arrow Function Expressions
Thus, the following examples are all equivalent:
(x) => { return Math.sin(x); }
(x) => Math.sin(x)
x => { return Math.sin(x); }
x => Math.sin(x)
so, is there a way to use the arrow operator and define a function on the prototype. something like,
c(x) => Math.sin(x)
回答1:
The valid syntax for arrow functions
is different from 'member location`. The "only" way to put functions on the prototype are via member function. Arrow function are actually member properties (which just happen to be functions). Your code is equivalent to the following:
export module A {
export class Test {
constructor(){}
a = function (x){ return Math.sin(x); }
b (x) : any { return Math.sin(x); }
}
}
And member properties go on this
not prototype
.
What you can do is define it as a member function and then override it in the constructor:
export module A {
export class Test {
constructor(){
this.a = (x)=> Math.sin(x);
}
a (x){ }
b (x) : any { return Math.sin(x); }
}
}
Even put it on the prototype if you want :
class Base {
constructor(){
Base.prototype.a = (x)=> Math.sin(x);
}
a (x){}
}
class Child extends Base{
constructor(){
super();
}
a(x){return super.a(x);}
}
var child = new Child();
console.log(child.a(Math.PI));
回答2:
What is wrong with just using a standard function ? i.e.
export module A {
export class Test {
constructor(){}
a =(x) => { return Math.sin(x); }
b (x) : any { return Math.sin(x); }
c(x:number): number {
return Math.sin(x);
}
}
}
来源:https://stackoverflow.com/questions/22314993/typescript-arrow-operator-to-define-a-function-on-prototype