为什么“this”的上下文在本例中进行更改
Why does the context of "this" change in this example?
我很不好意思承认我花了很多时间来解决这个问题。事实证明,当在原型addSong函数中使用"problem area"注释下的两行顺序改变了"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"包含一个jquery选择器,我在初始化PlaylistView对象时设置了这个选择器。然而,当我颠倒顺序时,查看Firefox中的检查器显示"this"指的是DOM中的实际表单。为什么呢?
原因是this.addSong !== $.proxy(this.addSong, this)
。当您运行$.proxy
和listenAddSong
时,使用绑定函数,this
是您的Playlist
对象。当您颠倒顺序时,未绑定的函数将传递给listenAddSong
中的侦听器。用这一行中的已绑定函数替换未绑定函数:
this.addSong = $.proxy(this.addSong, this);
因此,当listenAddSong
运行时,取决于this.addSong
指向哪个函数,您要么得到正确的行为,要么得到不正确的行为。
相关文章:
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- extjs中事件处理程序函数中的THIS上下文
- 在对象文字的声明中继承上下文(this)?“自我”还好吗
- 是否可以绑定javascript函数,使其本地上下文与“this”相同
- 当作为脚本运行时.js Node中“this”的上下文是什么
- 变量“this”上下文在重新赋值变量后未更新
- 浏览器化模块中的“this”上下文
- Node.js:在模块作用域中使用“this”运算符的上下文是什么
- 使用“this”时,函数会丢失上下文 - Raphael JS
- JavaScript承诺:具有绑定的深度嵌套上下文(this)
- d3.js/CoffeeScript:访问mouseover中类和路径的执行上下文(this)
- Angular服务"this"正在更改窗口对象的上下文
- 传递一个原型's函数作为参数而不丢失'this'上下文
- 全局上下文和“this”;在node . js
- ' this '在全局上下文中和内部函数中
- 保留'this'上下文
- 在回调中调用Js `this`上下文
- JS bind(),我需要两个“this”上下文
- 我如何传递一个非'this'上下文到函数
- 调用带有promise和'this'上下文