javascript - 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);
});
解决方案
.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 );
} );
推荐阅读
- c# - 获取从抽象类继承并在属性中具有特定值的类的实例
- javascript - How to import a class method into a React class
- ios - 我是否必须更新我的 iphone(到最新版本)才能将其与最新版本的 xcode 连接?
- r - 在 r 中绘制拟合线
- php - 如何使用php codeigniter解析csv数据并插入数据库
- jquery - jquery css的负边距
- java - 发送密钥在 selenium java 中不起作用
- java - 注释未调用 AOP
- php - PHP发送邮件错误:标题必须是一个数组
- c++ - 如何在 wxWidgets 中使用多线程?