首页 > 解决方案 > 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);
});

标签: javascript

解决方案


.bind(this)声明时使用function

像这样:

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 );
} );

推荐阅读