为什么“this”的上下文在本例中进行更改

Why does the context of "this" change in this example?

本文关键字:this 上下文 为什么      更新时间:2023-09-26

我很不好意思承认我花了很多时间来解决这个问题。事实证明,当在原型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)。当您运行$.proxylistenAddSong时,使用绑定函数,this是您的Playlist对象。当您颠倒顺序时,未绑定的函数将传递给listenAddSong中的侦听器。用这一行中的已绑定函数替换未绑定函数:

this.addSong = $.proxy(this.addSong, this);

因此,当listenAddSong运行时,取决于this.addSong指向哪个函数,您要么得到正确的行为,要么得到不正确的行为。