1

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 Answers2

0

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
-1

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)
ΔO 'delta zero'
  • 3,506
  • 1
  • 19
  • 31
  • This changes the semantics of the code in the OP. The variable `x` in the constructor (from the OP) is not directly visible via the property name "x" on the object; in your answer, it is. – Pointy May 16 '21 at 18:16