我有一个正在创建的类,当你在某件事上有两个函数时,我很难理解如何使用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
请使用括号表示法,如上所示