Using defineProperty() to Create Getter and Setter in Javascript Object
Last Updated: September 20, 2017
To create getter and setter for Javascript object I am going to use Object.defineProperty()
function
Now I will do getter and setter for the name property of the Product object
function Product(){ var name="", price=0 } Object.defineProperty(Product.prototype,"Name",{ get : function(){ return this.name }, set : function(value){ this.name=value } }) var product= new Product() product.Name="Fanta" console.log("Product Name is :"+ product.Name)
In line 7, You can see the defineProperty()
method with three argument
First argument is the prototype of the object and second argument is the name or the getter and setter. In this example I am using Name
.
Finally you have the third argument for make getter and setter functions