0

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)
hippietrail
  • 15,848
  • 18
  • 99
  • 158
bsr
  • 57,282
  • 86
  • 216
  • 316

2 Answers2

0

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));
basarat
  • 261,912
  • 58
  • 460
  • 511
0

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);
        }
    }
}
blorkfish
  • 21,800
  • 4
  • 33
  • 24
  • for the next reader :) c's "this" is not bound correctly when the function is used like 'map(this.c)'. "this" would become the person who called the function not the instance that has c. – David Stocking Jan 11 '19 at 19:40