簡體   English   中英

了解 Typescript,Angular 箭頭 function

[英]Understanding Typescript,Angular arrow function

我對 angular 很陌生。 盡管我嘗試了很多,但我不理解一些代碼片段。 誰能解釋以下 3 個函數如何與輸入、output 和主體一起工作。

private _rowClass: (row: T) => {[key: string]: boolean} = _ => {return {};};

  @Input() public set rowClass(func: (row: T) => {[key: string]: boolean}) {
    this._rowClass = func;
  }

  public get rowClass(): (row: T) => {[key: string]: boolean} {
    if (this.condition) {
      return _ => {return {};};
    }
    return this._rowClass;
  }

    @Input()
    public set rows(value: T[]) {
        this._rows = value
       }

在模板中

  <ngx-datatable
    [rowClass]="rowClass"
    [rows]="rows"
     >

首先我不得不說這段代碼真的很丑,而且違反了任何干凈的代碼規則。

TL;DR: 箭頭函數是 function 表達式,有助於將this scope 與父級保持聯系。 但是在這里使用它們是因為您必須在現代 JavaScript / TypeScript 中更喜歡箭頭 function。

private _rowClass: (row: T) => {[key: string]: boolean} = _ => {return {};};

這一行定義了一個使用變量名_作為參數的方法。 變量_rowClass現在是 function _ => {return {}}等於function (_) {return {};} 警告:變量名_不好。 使用 a-zA-Z0-9 作為變量名。 順便提一句。 參數_未使用,可以刪除。

請注意,例如_rowClass: <THIS>:之后的代碼只是 TypeScript 中的類型。 類型是(row: T) => {[key: string]: boolean}這意味着它是一個具有泛型類型參數row: T (T any type you pass) 的方法,它的返回值是一個 object 具有任何屬性具有 boolean 作為值的鍵。 [key: string]: boolean

public get rowClass(): (row: T) => {[key: string]: boolean} {

這只是具有相同類型定義的 getter get返回_rowClass ,或者在這種情況下,如果this.condition為真,它返回方法_ => {return {}}的新實例。

這是 JavaScript 中的簡化版本。 我刪除了復雜的 TypeScript 類型以保持清潔。 在這里只是為了演示。

class YourClass {
  // A private member accessible via setter and getter below.
  // The value is a function (which is also a class in ES5. Constructor function).
  _rowClass = function() {
    return {};
  };

  // The setter of the private property above.
  set rowClass(func) {
    this._rowClass = func;
  }

  // The getter of the private property above.
  // Returns a new constructor function if the property "condition" of this class is true.
  get rowClass() {
    if (this.condition) {
      return function() {
        return {};
      };
    }
    return this._rowClass;
  }

  // Just a method to set the private property _rows.
  set rows(value) {
    this._rows = value;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM