suprxd
suprxd

Reputation: 330

What happens when setting object property without setter in javascript

var vehicle = function(){
var type;
var tyre;

this.tellTyres = function(){
  console.log(type + " has " + tyre + " tyres");
};

this.__defineGetter__("type", function(){
  return type;
});
this.__defineSetter__("type", function(val){
  type = val;
});
this.__defineGetter__("tyre", function(){
  return tyre;
});
//   this.__defineSetter__("tyre", function(val){
//     tyre = val;
//   });

};

var car = new vehicle();
car.type = "Car";
car.tyre = 4;

console.log(car.tyre);

car.tellTyres();

I was learning about the getter and setter. Then I realized Javascript is not throwing any error while setting the value of car.tyre without having its setter method.

What happens to the car.tyre property outside the constructor. Where does the value 4 store? Does it override?

Upvotes: 2

Views: 2591

Answers (1)

PeterMader
PeterMader

Reputation: 7285

JavaScript objects are more like dictionaries than like Java objects. This means that you can set and get an object's properties just by using the property accessor operators . and []:

var obj = { foo: 'bar' };
obj.baz = 17;
console.log(obj.foo, obj.baz); // logs '"bar" 17'

And that is absolutely fine.

But sometimes, you want to do something whenever someone modifies a property of your object. In these cases, you define a getter or setter function for that property (use Object.defineProperty instead of defineGetter and defineSetter):

var obj = { foo: 'bar' };
Object.defineProperty(obj, 'baz', {
  get: function () {
    console.log('Someone wants to read the property "baz"!');
    return 34;
  },
  set: function (value) {
    console.log('You are not allowed to modify the property "baz"!');
  }
});

obj.baz = 17; // doesn't work
console.log(obj.foo, obj.baz); // logs '"bar" 34'

When you create a new vehicle(), you create a new object, on which you can set or read properties. You don't need the getters and setters.

Upvotes: 2

Related Questions