Object

Object

by Yogesh Rathod

JavaScript

//Object

function Person(){
var name = ""
return {
set : function(name){ this.name=name;},
get : function(){return this.name;}
}

}


var inst1 = new Person();
inst1.set('Yogesh');
//alert(inst1.get())

function Product(name,price) {
  this.name = name;
  this.price = price;
//this.discount = 0; // <- remove this line and refactor with the code below
  var _discount; // private member
  Object.defineProperty(this,"discount",{
    get: function() { return _discount; },
    set: function(value) { _discount = value; if(_discount>80) _discount = 80; },
  });
}
try{
var sneakers = new Product("Sneakers",20);

sneakers.discount = 50; // 50, setter is called
sneakers.discount+= 20; // 70, setter is called
sneakers.discount+= 20; // 80, not 90!
alert(sneakers.discount); // getter is called
}
catch(e1){
alert(e1.message + '\r\n ' + JSON.stringify(e1))
}