簡體   English   中英

JS static a Class 的方法無法調用其他方法:TypeError is not a function

[英]JS static method of a Class can't call other method: TypeError is not a function

我有一個 class 有兩種方法:

class Solution {
  swap(arr, idx1, idx2) {
    let temp = arr[idx1];
    arr[idx1] = arr[idx2];
    arr[idx2] = temp;
  }

  static bubbleSort(arr) {
    for (let i = arr.length; i > 0; i--) {
      for (let j = i - 1; j >= 0; j--) {
        if (arr[i] < arr[j]) this.swap(arr, i, j);
      }
    }
    return arr;
  }
}

當我調用Solution.bubbleSort([2,1,3])時,我得到TypeError: this.swap is not a function

當我將 swap() 設為 static 方法時它會起作用,但這不是我的意圖:

static swap(arr, idx1, idx2) { ... }

我嘗試使用構造函數將其綁定this bubbleSort() 方法,但沒有幫助,所以我猜這不是 scope 的問題?

constructor() {
  this.bubbleSort = this.bubbleSort.bind(this);
}

我也嘗試使用箭頭功能,但它也沒有幫助。

我理想的解決方案是將swap()作為私有輔助方法, bubbleSort()作為公共方法(就像在 Python 中一樣)。 但是我知道私有方法是一個提議,並沒有完全支持。

為什么當我將swap()設為 static 方法時它會起作用? 我怎樣才能寫得更好?

附言。 不看算法,我知道時間復雜度是 O(n2):P

我真的不明白為什么要使swap()成為實例方法。 但是如果你真的需要它,你可以創建一個臨時實例並使用它。

class Solution {
  swap(arr, idx1, idx2) {
    let temp = arr[idx1];
    arr[idx1] = arr[idx2];
    arr[idx2] = temp;
  }

  static bubbleSort(arr) {
    let temp_instance = new Solution;
    for (let i = arr.length; i > 0; i--) {
      for (let j = i - 1; j >= 0; j--) {
        if (arr[i] < arr[j]) temp_instance.swap(arr, i, j);
      }
    }
    return arr;
  }
}

但是實際上沒有任何理由讓swap()成為實例方法,因為它從不訪問它所調用的 object 的任何屬性。

您可以利用依賴注入來改進此代碼。

如果您的 function bubblesort() 將調用 swap(),您應該將 swap() 作為依賴項傳入。

static bubbleSort(arr, swap) {
    for (let i = arr.length; i > 0; i--) {
      for (let j = i - 1; j >= 0; j--) {
        if (arr[i] < arr[j]) swap(arr, i, j);
      }
    }
    return arr;
  }
}

你的 bubblesort() function 現在更簡單了,因為它不需要引用它自己的 scope 之外的任何東西。你最初關於 scope 的問題現在沒有實際意義,這是一件好事。

暫無
暫無

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

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