1

我一直在尝试使用 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);

谢谢

4

3 回答 3

2

在你的吸气剂中,你正在返回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);

于 2016-11-25T22:16:33.577 回答
2

您应该创建 Person 实例newPerson如您所见,您可以简单地将传递给构造函数的变量用于 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);

于 2016-11-25T22:23:21.223 回答
0

您需要保存对传递给构造函数的参数的引用,以便在实例化后获取/设置它们。

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);
于 2016-11-25T22:07:55.063 回答