Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để xóa một getter bằng cách sử dụng toán tử xóa trong JavaScript?


Để xóa một getter bằng cách sử dụng toán tử xóa, hãy sử dụng từ khóa xóa. Đây là cách bạn có thể xóa -

delete obj.name

Ví dụ

Bạn có thể thử chạy mã sau để tìm hiểu cách xóa getter

Bản trình diễn trực tiếp

<html>
   <body>
      <script>
         var department = {
            deptName: "Marketing",
            deptZone: "North",
            deptID: 101,
            get details() {
               return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
            },
            set details(info) {
               var res = info.toString().split(' ');
               this.deptName = res[0] || '';
               this.deptZone = res[1] || '';
               this.deptID = res[2] || '';
            }
         }
         department.details = 'Marketing North 001';
         document.write("<br>Department Name: " + department.deptName);
         document.write("<br>Departmet Zone: " + department.deptZone);
         document.write("<br>Department ID: " + department.deptID);
         delete department.deptName;
         document.write("<br>Department Name (after deletion): " + department.deptName);
      </script>
   </body>
</html>