在靜態 () 方法內使用 JavaScript


實際上,當我們嘗試在靜態方法內使用一個物件時,結果將是徒勞的。但將物件作為引數傳遞後,則可以訪問該物件。讓我們簡潔地探討一下。

示例-1

在下面的示例中,我們試圖直接使用物件“myComp”,而不是將它作為引數傳遞,因此,我們沒有得到任何結果。如果我們開啟瀏覽器控制檯,將出現一個錯誤提示“myComp.comp() 不是一個函式”。要獲取實際結果,我們必須如示例-2所示將物件作為引數傳遞

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
      static comp() {
         return "Tutorix is the best e-learning platform"
      }
   }
   myComp = new Company("Tesla");
   document.getElementById("method").innerHTML = myComp.comp();
</script>
</body>
</html>

示例-2

在下面的示例中,物件作為引數傳遞。因此,我們將獲得如輸出中所示的結果。

線上示例

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
      static comp(val) {
         return "Elon musk is the head of " + val.name
      }
   }
   myComp = new Company("Tesla");
   document.getElementById("method").innerHTML = Company.comp(myComp);
</script>
</body>
</html>

輸出

Elon musk is the head of Tesla

更新於: 2020 年 7 月 2 日

74 次瀏覽

職業生涯啟動

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.