如何在使用物件的屬性時丟擲錯誤?


在JavaScript中,物件以鍵值對的形式包含屬性。我們可以使用屬性名稱作為物件的引用來訪問物件的任何屬性。

有時,我們嘗試訪問物件中不存在的屬性。在這種情況下,我們將得到undefined值。讓我們透過下面的示例來理解它。

示例(訪問物件屬性)

在下面的示例中,我們建立了物件並添加了一些屬性。我們還添加了一些巢狀屬性。之後,我們嘗試訪問'prop5'屬性,它是'prop4'的巢狀屬性。使用者可以在輸出中觀察其值。

此外,我們嘗試訪問'prop6'屬性,而物件返回undefined,因為它在物件中不存在。

<html>
<body>
   <h2>Accessing the object properties in JavaScript</h2>
   <div id="content"> </div>
   <script>
      let content = document.getElementById('content');
      let object = {
         name: 'Shubham',
         prop1: 'Hello',
         prop2: 'World',
         prop3: '!',
         prop4: {
            prop5: 'This is a nested object.'
         }
      }
      content.innerHTML = "The value of prop5 is : " + object.prop4.prop5;
      content.innerHTML += "<br> The value of prop3 is : " + object.prop3;
      content.innerHTML += "<br> The value of prop6 is : " + object.prop6;
   </script>
</body>
</html>

因此,每當物件中不存在屬性時,我們可以丟擲一個錯誤,說明該屬性在物件中不存在。

在這裡,我們將學習一種不同的方法來在訪問物件屬性時丟擲錯誤。

使用“in”運算子在訪問物件屬性時丟擲錯誤

“in”運算子允許我們檢查屬性是否存在於物件中。我們可以使用鍵作為“in”運算子的左運算元,並將物件作為右運算元。

我們可以檢查屬性是否存在於物件中。如果不存在,我們可以丟擲一個錯誤。

語法

使用者可以按照以下語法使用“in”運算子在訪問物件屬性時丟擲錯誤。

if(key in obj){
}else {
   // throw error
}

在上述語法中,key是要檢查其是否存在於物件中的屬性。

示例

在下面的示例中,我們建立了table_obj物件並添加了一些鍵值對。名為get_property_value()的函式檢查屬性是否存在於物件中。如果屬性存在於物件中,則返回屬性值。否則,它會丟擲一個錯誤。

在try-catch塊中,我們捕獲錯誤。在輸出中,使用者可以觀察到get_property_value()函式為'table_price1'屬性丟擲錯誤,而不是為該屬性返回undefined值。

<html>
<body>
   <h3>Using the <i> in </i> operator  to throw an error while accessing the object properties in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      // creating an object for table details
      let table_obj = {
         table_name: "table1",
         table_type: "table",
         table_size: "10x10",
         table_color: "black",
         table_price: 1000
      }
      function get_property_value(key) {
         if (key in table_obj) {
            return table_obj[key];
         } else {
            throw new Error(key + " is not a valid property name.");
         }
      }
      try {
         content.innerHTML += "table_name : - " + get_property_value("table_name");
         content.innerHTML += "<br>" + get_property_value("table_price1");
      } catch (e) {
         content.innerHTML += "<br>" + e.message;
      }
   </script>
</body>
</html>

使用defineProperty()方法在訪問物件屬性時丟擲錯誤

Javascript的defineProperty()方法允許我們向物件新增屬性。我們可以為丟擲錯誤的屬性描述符新增getter。

語法

使用者可以按照以下語法使用defineProperty()方法在訪問物件屬性時丟擲錯誤。

Object.defineProperty(obj_name, 'prop_name', {
   get: () => {
      // throw an error
   }
});

在上述語法中,我們將描述符作為defineProperty()方法的第三個引數傳遞。我們可以為物件的特定屬性從描述符函式中丟擲錯誤。

引數

  • **Obj_name** − 這是向其中新增屬性的物件的名稱。

  • **Prop_name** − 這是要新增到物件的屬性名稱。

  • **{ get: () => { } }** − 這是物件屬性的getter函式。

示例

在下面的示例中,我們建立了沒有屬性的empty_obj物件。我們使用defineProperties()方法新增屬性。作為描述符,我們添加了get()方法,該方法會丟擲一個包含錯誤訊息的錯誤。

在輸出中,使用者可以觀察到當我們嘗試訪問'prop1'屬性時會丟擲錯誤。

<html>
<body>
   <h3>Using the <i> defineProperty() </i> method to throw an error while accessing the object properties in JavaScript </h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let empty_obj = {};
      Object.defineProperty(empty_obj, 'prop1', {
         get: () => {
            throw new Error('You cannot access prop1 property');
         }
      });
      try {
         content.innerHTML = "The value of prop1 property in the empty object is " + empty_obj.prop1;
      }
      catch (err) {
         content.innerHTML = "The error is : - " + err;
      }
   </script>
</body>
</html>

在訪問物件屬性時使用Proxy()建構函式丟擲錯誤

Proxy()建構函式允許我們為物件建立一個代理,並覆蓋物件的全部描述符,例如getter和setter。在這裡,我們可以覆蓋getter()並編寫一個可以丟擲錯誤的新函式。

語法

使用者可以使用以下語法使用Proxy()建構函式在訪問物件屬性時丟擲錯誤。

let proxy_obj = new Proxy(target_Obj, {
   get: function (target, prop) {
      // throw error
   },
});

在上述語法中,target_obj是要為其建立代理的物件。我們將包含get()方法的物件作為第二個引數傳遞。在get()方法中,我們可以驗證物件屬性,如果物件屬性無效,則丟擲錯誤。

示例

在下面的示例中,我們使用Proxy()建構函式為targetObj物件建立了代理。在建立代理時,我們檢查使用者是否訪問了'prop5'屬性。如果沒有,我們將始終丟擲錯誤。這意味著只能從物件訪問'prop5'屬性。但是,它將為'prop5'屬性返回undefined值,因為我們沒有在物件中定義它。

<html>
<body>
   <h3>Using the <i> defineProperty() </i> method to throw an error while accessing the object properties in JavaScript </h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let targetObj = {
         prop1: 'Hello',
      }
      let proxy_obj = new Proxy(targetObj, {
         get: function (target, prop) {
            if (prop != 'prop5') {
               throw new Error('You are only allowed to access prop5');
            }
         },
      });
      try {
         content.innerHTML += "The value of prop1 is: " + proxy_obj.prop1 + "<br>";
      } catch (e) {
         content.innerHTML += "The error is - " + e + "<br>";
      }
   </script>
</body>
</html>

更新於:2023年4月5日

519 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告