JavaScript 中的 getter 和 setter 有什麼區別?


Getter

當訪問某個屬性時,將會透過隱式呼叫某個函式獲得其值。JavaScript 中使用“get”關鍵字。Set 允許使用識別符號,即數字或字串。

Setter

當設定某個屬性時,將會隱式呼叫某個函式,並且作為引數傳遞一個值。利用 ello,返回值將被設定為屬性本身。JavaScript 中使用“get”關鍵字。Set 允許使用識別符號,即數字或字串。

示例

這裡有一個示例,展示瞭如何實現 getter 和 setter

即時演示

<html>
   <body>
      <script>
         var department = {
            deptName: "Finance",
            deptZone: "South",
            deptID: 105,
            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(department.deptName);
         document.write(department.deptZone);
         document.write(department.deptID);
      </script>
   </body>
</html>

更新日期:2020 年 6 月 16 日

816 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.