【问题标题】:typescript arrow operator to define a function on prototype打字稿箭头运算符在原型上定义一个函数
【发布时间】:2015-04-20 17:10:19
【问题描述】:

example 所示,分配给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)

【问题讨论】:

    标签: javascript typescript arrow-functions


    【解决方案1】:

    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));
    

    【讨论】:

      【解决方案2】:

      只使用标准函数有什么问题?即

      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);
              }
          }
      }
      

      【讨论】:

      • 给下一位读者 :) 当函数像 'map(this.c)' 一样使用时,c 的 "this" 没有正确绑定。 “this”将成为调用函数的人,而不是具有 c 的实例。
      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 2017-01-04
      • 2016-08-26
      • 2015-12-12
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多