0

Okay, this question might seem silly but I'm learning object oriented concepts in javascript into more depth so to avoid confusions I had to ask this anyway.

    const ObjConstructor = function() {
    this.name = 'object';
    let value = 1;

    this.destroyValue = function() {
        value = 0;
    }

    this.getValue = function() {
        return value;
    }
    }

The above code implements an object constructor function, and it has a private member value. The way I assume how this works every time an object is created using this constructor is it basically calls the call() method on ObjConstructor object and returns the object with members (in this case it is name, destroyValue and getValue) assigned to it.

But I get so confused when understanding how destroyValue and getValue methods could be able to access the private variable value here. Because it is not a member of the current object the methods are called on, and also value which is a local variable of the constructor function was got destroyed after the first time it executed the constructor function to create the object.

yasmikash
  • 157
  • 2
  • 14
  • 1
    Well in your example `value` is a *global* variable, not a private; there's no `let` or `var` or `const` declaration. – Pointy Nov 11 '19 at 02:44
  • @Pointy sorry that was a mistake, value should be declared by the way – yasmikash Nov 11 '19 at 02:45
  • Anyway the answer is that `value` is in the *closure* created by the call to the constructor. – Pointy Nov 11 '19 at 02:49
  • @Pointy sorry i still don't get this – yasmikash Nov 11 '19 at 05:32
  • [Here's an old but rich source of information](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) — and [here is an MDN article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). Closures are an extremely important concept in JavaScript programming. – Pointy Nov 11 '19 at 13:10
  • okay, but what I don't understand is even though one instance can change `value` using `destroyValue()` method, `value` still has its initial value for other instances. how this relates to closure? – yasmikash Nov 12 '19 at 17:38
  • The closure is like a "shadow" object. You can't mess with it like a normal object, but it's where all the local variables of a function live, and a new one is created for each function call. That's a simplification, but it's true that the local variables in the constructor "stay alive" forever from each call to the constructor, and those functions declared inside can access and modify the closure variables. – Pointy Nov 12 '19 at 21:36

0 Answers0