什么是 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.