【发布时间】:2015-09-20 01:48:47
【问题描述】:
我很尴尬地承认我花了多少时间试图解决这个问题。原来“问题区”注释下的两行的顺序在原型addSong函数中使用时改变了“this”的上下文。
var PlaylistView = function(config){
this.config = config || {};
this.$addSongForm = this.config.addSongForm || $('#addSongForm');
this.$song = this.config.song || $('#song');
// problem area
this.addSong = $.proxy(this.addSong, this);
this.listenAddSong();
};
PlaylistView.prototype.listenAddSong = function(){
this.$addSongForm.on('submit', this.addSong);
};
PlaylistView.prototype.addSong = function(event){
//Here is where I'm getting different context for this
var songName = this.$song.val();
//do some stuff...
return false;
};
return PlaylistView;
当这两行按显示的顺序排列时,我得到了我想要的行为:“this.$song”包含一个我在初始化 PlaylistView 对象时设置的 jquery 选择器。但是,当我将顺序颠倒过来时,查看 Firefox 中的检查器显示“this”指的是 DOM 中的实际表单。 这是为什么呢?
【问题讨论】:
-
没有人能确定你的代码中
this指的是什么,因为this的值可以用.apply或.bind或.call随意更改,等等。
标签: javascript jquery scope