【问题标题】:Why does the context of "this" change in this example?为什么这个例子中“this”的上下文发生了变化?
【发布时间】: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


【解决方案1】:

原因是因为this.addSong !== $.proxy(this.addSong, this)。当您运行$.proxy 然后listenAddSong 使用绑定函数并且this 是您的Playlist 对象。当您颠倒顺序时,unbound 函数将传递给listenAddSong 中的侦听器。您在这一行中用绑定函数替换未绑定函数:

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

因此,根据this.addSong 所指向的函数listenAddSong 运行时,您要么得到正确的行为,要么得到不正确的行为。

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多