Getter and Setter Creating with Constructor Function in Javascript

Last Updated: September 20, 2017

You can create getter and setter for the objects created with constructor function in javascript. To create the setter you can use the function and to create getter you can use the 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

function Product(){"",

var product= new Product()
console.log("Product Name is :"+ product.getName)
  • 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>