JS:从封闭函数内访问对象中的数据的问题

时间:2017-01-31 21:11:20

标签: javascript function javascript-objects

我希望用this-keyword引用对象内的东西。 我希望所有数据都在一个对象中。 现在我问自己如何从其他函数中访问数据。

我不知道。

    var composer = {
      currentChordType: [],

      setChordType: function() {
        this.currentChordType = [5, 4];
      },

      getNextChord: function() {
        var index = Math.floor(Math.random() * 3);
        switch (index) {
          case (0):
            {
              switch (this.currentChordType[0]) {
                /* more code .... */
              }
            }
            /* more code .... */
        }
      }
    }

    composer.setChordType();
    composer.getNextChord();

错误是:Uncaught TypeError: Cannot read property '0' of undefined

产生问题的一行是:switch (this.currentChordType[0]) {

2 个答案:

答案 0 :(得分:1)

我打赌,你没有提供给我们的真实的,真实的,破坏性的代码会做类似button.addEventListener("click", composer.getNextChord)之类的东西,或类似回调的地方。在这种情况下,您需要bind方法到作曲家对象。

定义作曲家后,将方法绑定到它:

var composer = {
   ...
   getNextChord: function() { ... }
};

// Add this bit:
composer.getNextChord = composer.getNextChord.bind(composer);

答案 1 :(得分:0)

看起来范围在switch语句中变得混乱。开发人员通常通过将this分配给另一个变量然后在其他地方访问它来保留范围。所以试试这个

 getNextChord: function() {
    var that = this;
    var index = Math.floor(Math.random() * 3);
    switch (index) {
      case (0):
        {
          switch (that.currentChordType[0]) {
            /* more code .... */
          }
        }
        /* more code .... */
    }
  }