Javascript& jQuery - 理解“this”上下文 - 意外“。”期

时间:2013-12-21 15:22:33

标签: javascript jquery object

我有一个我正在创建的课程,当你有两个功能时,我很难理解如何使用this

在我的init函数中,this引用了类对象,但在我的jQuery .each()语句中,this引用了您正在迭代的任何元素。因此,我将对类对象的引用保存在名为tempThis的变量中。但这导致错误:

$.Audio = function() {}

$.Audio.prototype = {
  init: function() {
    this.notes = {};
    var tempThis = this;
    $('audio').each({
      // I'm getting an "Unexpected Token ." on this line
      // Right after tempThis
      tempThis.notes.$(this).id = $(this).id + " note";
    })
  }
}

我的想法是this.notes包含key: value对的对象,例如{ 'C': 'C note'},其中C是我抓住的audio标记的ID .each()声明。

为什么我会遇到这个意外的时期错误?这是错误的做法吗?

我也试过这个:

tempThis.notes[$(this).id] = $(this).id + " note";

但我仍然在tempThis之后收到错误。

1 个答案:

答案 0 :(得分:2)

.each()期望一个函数作为参数,您在function()行中缺少each()

$.Audio = function () {}

$.Audio.prototype = {
    init: function () {
        this.notes = {};
        var tempThis = this;
        $('audio').each(function () {//missing function() here
            tempThis.notes[this.id] = this.id + " note";
        })
    }
}

另外,要访问音频元素的ID,您需要使用this.id$(this).prop('id'),并访问tempThis.notes的变量键属性,使用括号表示法,如上所示