typescript arrow operator to define a function on prototype

风格不统一 提交于 2019-12-12 00:58:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!