簡體   English   中英

如何使用object.defineproperty在javascript中定義getter和setter

[英]How to define getters and setters in javascript using object.defineproperty

我一直在嘗試使用object.defineproperty編寫getter和setter方法,但是不能。我一直在嘗試此示例,但是由於未定義firstName屬性,它引發了錯誤。有人可以幫幫我嗎

 function person(fName, lName) { Object.defineProperty(this, 'firstName', { get:function() { return firstName; }, set:function(newValue){firstName=newValue;} }); } var p1=person("xyz","abc"); console.log(p1.firstName); 

謝謝

在您的getter中,您將返回firstName ,但尚未定義,因此在Object.defineProperty上方聲明firstName並將fName參數分配給它。

同樣,在聲明p1時,請使用new運算符,以便您的person構造函數起作用並將"xyz"分配給firstName屬性。

因此,請嘗試以下操作:

 function person(fName, lName) { var firstName = fName; Object.defineProperty(this, 'firstName', { get:function() { return firstName; }, set:function(newValue){firstName=newValue;} }); } var p1 = new person("xyz","abc"); console.log(p1.firstName); p1.firstName = "abc"; console.log(p1.firstName); 

您應該new Person來創建Person實例。 如您所見,您可以簡單地將傳遞給構造函數的變量用於getter和setter。
我特意命名了構造函數參數,以查看所有變量如何一起發揮作用。

在您的getter中,您返回firstNameFromConstructor變量,或進行一些處理然后返回它。
在您的設置器中,您可以更改firstNameFromConstructor變量的值。

 function Person(firstNameFromConstructor, lastNameFromConstructor) { Object.defineProperty(this, 'firstName', { get:function() { return firstNameFromConstructor; }, set:function(newFirstName){ firstNameFromConstructor = newFirstName;} }); Object.defineProperty(this, 'lastName', { get:function() { return lastNameFromConstructor; }, set:function(newLastName){ lastNameFromConstructor = newLastName;} }); } var p1= new Person("xyz","abc"); console.log(p1.firstName); p1.firstName = 'zyx' console.log(p1.firstName); 

您需要保存對傳遞給構造函數的參數的引用,以便可以在實例化之后獲取/設置它們。

function person(fName, lName) {    
  Object.defineProperty(this, 'firstName', {
    get: function () { return this._firstName; },
    set: function (newValue) { this._firstName = newValue; }
  });

  Object.defineProperty(this, 'lastName', {
    get: function () { return this._lastName; },
    set: function (newValue) { this._lastName = newValue; }
  });

  this.firstName = fName;
  this.lastName = lName;
}

var p1 = new person("xyz", "abc");
console.log(p1.firstName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM