Search code examples
javascripthtmldefineproperty

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


I have been trying to write getters and setters using object.defineproperty,but could not .I have been trying this example but it throws an error as no firstName property defined.can someone please help me this

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);

Thanks


Solution

  • You should new up your Person to create the Person instance. As you can see, you can simply use the variables that you passed into the constructor for your getter and setter.
    I purposely named the constructor parameters to see how all the variables play together.

    In your getter, you return the firstNameFromConstructor variable, or do some processing and then return it.
    In your setter, you can change the value of the firstNameFromConstructor variable.

    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);