Why does the value of x is not updating ? is there anything wrong with the code ? i'm new to javascript

120 Views Asked by At

var ModuelPattern=(function () {
    var x="A"
    var change=function(){
        if(x==="A"){
            x="B"
        }
        else{
            x="A"
        }
    }
    return{
        x:x,
        f:change
    }
  })();
  
  ModuelPattern.f()
  console.log(ModuelPattern.x)
  

I cannot figure out an way to update x inside IIFE using revealing-module pattern and access outside the Scope

2

There are 2 best solutions below

1
ΔO 'delta zero' On

Use this keyword to access object's own properties.

var ModuelPattern=(function () {
    this.x = "A"
    this.change=function() {
        if(this.x==="A"){
            this.x = "B"
        }
        else{
            this.x = "A"
        }
    }
    return {
        x: this.x,
        f: this.change
    }
})();

console.log(ModuelPattern.x)
ModuelPattern.f()
console.log(ModuelPattern.x)

0
Pointy On

You can make x a getter function in the returned object:

var ModuelPattern=(function () {
    var x="A"
    var change=function(){
        if(x==="A"){
            x="B"
        }
        else{
            x="A"
        }
    }
    return{
        get x() { return x; },
        set x(_) {},
        f:change
    }
  })();
  
  ModuelPattern.f()
  console.log(ModuelPattern.x)

That allows the returned object to access the local variable in the closure formed from calling the original factory function. I added a dummy setter function as an illustration.