Javascript & jQuery - 了解"this"上下文 - 意外"."时期



我有一个正在创建的类,当你在某件事上有两个函数时,我很难理解如何使用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是我在.each()语句中获取的audio标签的id。

为什么我会收到这个意外的经期错误?这是错误的方法吗?

我也试过这个:

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

但是tempThis后我仍然收到错误.

>.each()需要一个函数作为参数,那么您在each()行中缺少function()

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

还要访问需要使用 this.id$(this).prop('id') 的音频元素的 id,以及访问 的可变键属性tempThis.notes请使用括号表示法,如上所示

最新更新