I just curious about this question in my head about lock/fixed method in oop javascript. This is the example :
function Counter() {
this.count = 0;
this.increaseCount = function() {
this.count++;
}
this.displayCount = function() {
console.log(this.count);
}
}
var counter1 = new Counter();
counter1.increaseCount = function() {
this.count += 2;
}
counter1.increaseCount();
counter1.displayCount(); // 2
How to lock/fixed method so it cannot be changed by instances? In example I want to lock increase method always add one.
Edit : I think its different from read-only properties, because it's property. I very curious about method lock/fixed in javascript. Even i use
Object.defineProperty(Counter.prototype, 'increaseCountt', {
get: function() { this.count++; },
writtable: false
});
i called it "counter1.increaseCountt" not "counter1.increaseCountt()" because it's not method.
When i used Object.freeze after creating instance like this:
var counter1 = new Counter();
Object.freeze(counter1);
the count result always zero.