我有一个对象,其中有两个函数,正如我猜测的那样,每个函数都有不同的 this
值:
custom_controls : {
play_pause : function () {
console.log(this); // object
videoPlayer.getIsPlaying(function (video_is_playing) {
if (video_is_playing) {
console.log(this); // window
videoPlayer.pause(true);
} else {
videoPlayer.play();
}
});
}
},
然后该函数的调用如下:
custom_controls.play_pause()
我听说调用函数的方式表示 this
的值。
所以我的问题是:这里发生了什么?我使用什么类型的函数调用?每一项如何影响this
?
最佳答案
调用obj.func()
时, this
函数内部将等于 obj
。如果没有obj
,则使用全局对象 ( window
)。或者如果您正在 Strict Mode 中运行, undefined
已使用。
第一个日志是您的对象,因为您像这样调用该函数:
custom_controls.play_pause() // custom_controls will be 'this'
第二个日志是 window,因为该函数作为参数传递给 getIsPlaying
未使用任何 this
进行调用:
videoPlayer.getIsPlaying = function(callback) {
callback(); // this inside callback will be window
}
您可以控制 this
的值将是当您使用 call
调用函数时或apply
。您可以创建一个新函数,该函数始终具有 this
使用bind
将值设置为您想要的任何值功能:
videoPlayer.getIsPlaying(function (video_is_playing) {
if (video_is_playing) {
console.log(this); // my obj
videoPlayer.pause(true);
} else {
videoPlayer.play();
}
}.bind(this)); // magic!
引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
关于javascript - 以下 Javascript 函数如何影响 'this' 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20145740/