0

如本所示,分配a和定义b导致不同的函数类型。

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)

那么,有没有办法使用箭头运算符并在原型上定义一个函数。就像是,

 c(x) => Math.sin(x)
4

2 回答 2

0

的有效语法arrow functions不同于“成员位置”。将函数放在原型上的“唯一”方法是通过成员函数。箭头函数实际上是成员属性(恰好是函数)。您的代码等效于以下内容:

export module A {
    export class Test {
        constructor(){}               
        a = function (x){ return Math.sin(x); }
        b (x) : any { return Math.sin(x); }
    }
}

并且成员属性继续this没有prototype

您可以做的是将其定义为成员函数,然后在构造函数中覆盖它:

export module A {
    export class Test {
        constructor(){
            this.a =  (x)=> Math.sin(x);
        }               
        a (x){ }
        b (x) : any { return Math.sin(x); }
    }   
}

如果您愿意,甚至可以将其放在原型上:

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));
于 2014-03-11T03:01:55.117 回答
0

仅使用标准功能有什么问题?IE

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);
        }
    }
}
于 2014-03-11T03:03:36.170 回答