打字稿箭头运算符,用于在原型上定义函数 [英] typescript arrow operator to define a function on prototype
问题描述
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); }
}
}
这会导致以下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;
})();
但是,我对规范 4.9.2箭头函数表达式
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)
推荐答案
arrow functions
的有效语法与成员位置"不同.将函数放在原型上的唯一"方法是通过成员函数.箭头函数实际上是成员属性(恰好是函数).您的代码等效于以下内容:
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); }
}
}
成员属性在this
而不是prototype
上显示.
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));
这篇关于打字稿箭头运算符,用于在原型上定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!