作用域问题嵌套Javascript对象

3
我正在使用jQuery编写一些Javascript代码,以在浏览器中显示特别格式化的小部件。我已经取得了成功,但现在我正在重新设计我的代码有两个原因:
(1)我希望能够轻松地多次使用小部件,并有一个Javascript对象引用每个小部件。
(2)我希望按照正确的方式进行操作,以使我的代码完全可重用,并且不会在全局命名空间中留下各种对象和函数。
我遇到了作用域问题,希望解决这个问题并提高我的Javascript作用域理解。我将这个问题简化为一个小代码片段,以说明我正在做什么:
  function getMyObject() {
      var theObject = {
          doThis: function () { },
          doThat: function () { },
          combinations: {
              doThisTwice: function () { doThis(); doThis(); },
              doThatTwice: function () { doThat(); doThat(); }
          }
      };
      return theObject;
  }

  var myObject = getMyObject();
  myObject.combinations.doThisTwice();

我已经声明了一个返回对象的函数。
然而,当我尝试执行函数`combinations.doThisTwice()`时,程序会抛出一个错误,指出`doThis()`超出了范围。如何在`combinations.doThisTwice`的范围内引用函数`doThis`?
更新:感谢您对我的问题的回答:在函数`doThisTwice()`内部使用`theObject.doThis()`替换`doThis()`。这样做是有效的,但我不明白为什么。
我本以为,直到对象声明结束之前,名称`theObject`都无效。我认为我可能误解了Javascript的一些基本方面...可能是因为C语言风格的语法。

是的,JS就是这样奇怪。搜索JavaScript作用域和闭包,你会更好地理解作用域的工作原理。 - Mrchief
3个回答

2

doThis在函数作用域中未定义,因此它将遍历作用域链,但不会找到它。

您可以通过以下方式引用它:

theObject.doThis();

然而,如果你像这样定义你的函数,会更易读:

  function getMyObject() {
      function doThis() {};
      function doThat() {};

      var theObject = {
          doThis: doThis,
          doThat: doThat,
          combinations: {
              doThisTwice: function () { doThis(); doThis(); },
              doThatTwice: function () { doThat(); doThat(); }
          }
      };
      return theObject;
  }

但是在这种情况下,无论何时您从外部更改 doThisdoThisTwice 仍将引用原始函数。

2

你需要做的是:

function getMyObject() {
    var theObject = {
        doThis: function () { },
        doThat: function () { },
        combinations: {
            doThisTwice: function () { theObject.doThis(); theObject.doThis(); },
            doThatTwice: function () { theObject.doThat(); theObject.doThat(); }
        }
    };
    return theObject;
}

变量myObject = getMyObject(); myObject.combinations.doThisTwice();

您可以从外部作用域引用“theObject”以调用内部对象的函数。


尝试使用原型从theObject继承或将theObject复制到另一个变量中,它将不再起作用。如果您只是通过其变量引用对象,为什么需要首先使用this - Gherman

0

doThisTwice中,请使用theObject.doThis();而不是doThis();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接