什麼是 JavaScript 類和代理?


在本文中,我們將探討 **類** 和 **代理**,以及兩者之間的區別。

JavaScript 中的 **類** 類似於函式。唯一的區別在於它使用 class 關鍵字而不是 function。函式和類之間另一個重要的區別是,函式可以在定義之前就被呼叫。而類物件在使用前必須先定義,以防止丟擲任何引用錯誤。

語法

class Classname {
   constructor(property1, property2) {
      this.property1 = property1;
      this.prop erty2 = property2;
   }
}

示例 1

在本例中,我們將使用弱集中的方法,並瞭解如何在各種情況下使用它。

#檔名:index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Classes and Proxies</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      class Student {
         constructor(name, id) {
            this.name = name;
            this.id = id;
         }
      }
      let student = new Student("Steve", 101);
      console.log(student);
   </script>
</body>
</html>

輸出

它將在控制檯中產生以下輸出。

Student {name: 'Steve', id: 101}

**類表示式** - 我們也可以使用類表示式來定義類。類表示式可以分為兩種型別:命名和未命名。類的名稱可以透過 name 屬性訪問。

語法

let Employee = class {
   constructor(name, id) {
      this.name = name;
      this.id = id;
   }
}

示例 2

#檔名:index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Classes and Proxies</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Unnamed class
      let student = class {
         constructor(name, id) {
            this.name = name;
            this.id = id;
         }
      }
      console.log(student.name);
      // Named class
      let studentV2 = class junior {
         constructor(name, id) {
            this.name = name;
            this.id = id;
         }
      }
      console.log(studentV2.name);
   </script>
</body>
</html>

輸出

它將在控制檯中產生以下輸出。

student
27 junior

**代理** - 這些是用於細化物件基本操作的物件。它允許使用者建立另一個物件的代理。

引數

代理接受兩個引數,它們是 -

  • **目標** - 這是需要包裝代理的原始物件。

  • **處理程式** - 此物件屬性定義如果對該代理執行操作,則代理的行為。

語法

const target = {
   property1: "first property",
   property2: "second property"
};
const handler = { ... };
const proxy1 = new Proxy(target, handler);

示例 3

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Classes and Proxies</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      const target = {
         property1: "Tutorials Point",
         property2: "SIMPLY LEARNING"
      };
      const handler = {
         get: function (target, prop, receiver) {
            if (prop === "property2") {
               return "Start your Learning journey today !";
            } else {
               return Reflect.get(target,prop);
            }
         }
      }
      const proxy = new Proxy(target, handler);
      console.log(proxy.property1);
      console.log(proxy.property2);
   </script>
</body>
</html>

輸出

它將在控制檯中產生以下輸出。

Tutorials Point
Start your Learning journey today !

更新於: 2022-04-28

137 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.