1

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.

7
  • Create an instance factory and Object.freeze the instance before returing. Commented May 25, 2018 at 18:22
  • 2
    Possible duplicate of Defining read-only properties in JavaScript Commented May 25, 2018 at 18:23
  • I think that only for properties, even i use "get" function to call function it's still property @lealceldeiro Commented May 25, 2018 at 18:27
  • Did, the suggestion made by @Derek朕會功夫 work for you? It seems fine to me. What do you say about it? Commented May 25, 2018 at 18:33
  • @Derek朕會功夫 sorry i didnt understand when to add Object.freeze, can you explain again Commented May 25, 2018 at 18:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.