我有一个使用backbone.js 编写的简单音乐应用程序。我在我的模型之一中使用以下代码时遇到问题:
MyApp.Models.Program = Backbone.Model.extend({
toPlaylist: function(options, callback) {
console.log("Converting program to playlist");
var self = this;
console.log(self.get('name'));
this.stationHasLicense(function (licensedStation) {
console.log(self.get('name')); // Uncaught TypeError: Cannot call method 'get' of undefined
// bunch of other logic
});
},
});
第一个 self.get 工作正常。然而,stationHasLicense 回调中的第二个 self.get 会抛出错误。我在应用程序的其他区域使用 var self = this 来保持范围,但我不确定为什么这个实例失败。
最佳答案
尝试使用 underscore 中的绑定(bind)执行函数时绑定(bind)this上下文。
MyApp.Models.Program = Backbone.Model.extend({
toPlaylist: function(options, callback) {
console.log("Converting program to playlist");
var self = this;
console.log(self.get('name'));
this.stationHasLicense(_.bind(function (licensedStation) {
console.log(this.get('name'));
// bunch of other logic
}, this));
},
});
可以找到有关 that=this 或 self=this 主题的更多讨论:
关于javascript - Backbonejs 范围问题,变量以某种方式变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653466/