【问题标题】:Why does the value of x is not updating ? is there anything wrong with the code ? i'm new to javascript为什么 x 的值没有更新?代码有什么问题吗?我是 javascript 新手
【发布时间】:2021-08-06 03:24:35
【问题描述】:

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)
  

我想不出一种方法来使用显示模块模式更新 IIFE 内部的 x 并在外部访问 范围

【问题讨论】:

    标签: javascript module node-modules es6-modules revealing-module-pattern


    【解决方案1】:

    您可以在返回的对象中将x 设为getter 函数:

    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)
    

    这允许返回的对象访问由调用原始工厂函数形成的闭包中的局部变量。我添加了一个虚拟 setter 函数作为说明。

    【讨论】:

      【解决方案2】:

      使用this关键字访问对象自身的属性。

      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)

      【讨论】:

      • 这会改变 OP 中代码的语义。构造函数中的变量x(来自OP)不能通过对象上的属性名称“x”直接可见;在你的回答中,是的。
      猜你喜欢
      • 1970-01-01
      • 2018-08-19
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多