ES5 Way of Defining Getter and Setter for Javascript Object

Last Updated: September 20, 2017

You can use following ES5 code to define getter and setter for Javascript object.

function Product(){
    this._name="",
    this.price=0
    
}

Product.prototype={
    set name(value){
        this._name=value
    },
    get name(){
        return this._name
    }
}

var product= new Product()
product.Name="Fanta"
console.log("Product Name is :"+ product.Name)

In line 7, you have the Product.prototype to define the getter and setter