Getter and Setter Creating with Constructor Function in Javascript

You can create getter and setter for the objects created with constructor function in javascript. To create the setter you can use the Object.__defineSetter__.call() function and to create getter you can use the Object.__defineGetter__.call() function. You have to pass three parameters to the call() function.

First parameter is the prototype of the object, second parameter is the name of the getter or setter and third parameter is the function

Now I will do getter and setter for the name property of the Product object

  • Line 7 : I have defined the setter for name property, name of the setter is setName
  • Line 11: I have defined the getter for name property, name of the getter is getName
  • Line 16: Creating the object
  • Line 17: Using the setter to set name property
  • Line 18: Using the getter to get name property and print it in browser console/li>

Leave a Reply

Your email address will not be published. Required fields are marked *