Javascript:在将函数作为 arg 传入时携带"this"上下文



我知道胖箭头可以通过上下文,例如:

test() => {
// the fat arrow passes "this" context into here
}

但我现在使用的是videojs,它传递了一个onPlayerReady函数,我唯一的解决方案是引用this并在其中使用它。我试着在这里用一个肥箭,但没有用。

let that = this;
let player = videojs('videoPlayer', options, function onPlayerReady() {
this.play();
that.$store.commit('test', true);
});

在声明function时使用.bind(this)

像这样:

let player = videojs('videoPlayer', options, function onPlayerReady() {
this.play();
this.$store.commit('test', true);
}.bind(this) );

上面的代码相当于:

const callback = function() {
this.play();
this.$store.commit('test', true);
};
const boundCallback = callback.bind(this);
let player = videojs( 'videoPlayer', options, boundCallback );

也就是说,下面的代码应该有效-我很好奇为什么它不适用于你:

let player = videojs( 'videoPlayer', options, /*onPlayerReady:*/ () => {
this.play();
this.$store.commit( 'test', true );
} );

更新:

您说过.play()player对象上的函数属性,我假设$store是您的对象中的属性(而不是player(,在这种情况下:

  • 不要使用胖箭头函数/lambda,使用传统的匿名函数
  • 不要使用.bind(this)
  • 您需要使用闭包来传递父级/包含this(即父组件的this(,但我建议使用比that更好的名称,例如parentComponent

如此:

const parentComponent = this;
let player = videojs( 'videoPlayer', options, /*onPlayerReady:*/ function() {
this.play();
parentComponent.$store.commit( 'test', true );
} );

最新更新