如何作為一個函式和方法呼叫一個函式?


以下是作為函式和方法呼叫函式的程式碼-

示例

 線上演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result{
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Invoke a function as function and method</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to invoke function as function and method
</h3>
<script>
   let resEle = document.querySelector(".result");
   function add(a,b){
      return a+b;
   }
   let obj = {
      firstName:'Rohan',
      lastName:'Sharma',
      welcome(){
         return 'Welcome '+this.firstName+' '+this.lastName;
      }
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = 'Function invocation add(2,3) : ' + add(2,3) + '<br>';
      resEle.innerHTML += 'Method invocation obj.welcome() : ' + obj.welcome() + '<br>';
   });
</script>
</body>
</html>

輸出

以上程式碼將生成以下輸出 −

單擊“單擊此處”按鈕後 −

更新於: 16-Jul-2020

100 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.