Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

javascript - The context of this in a callback function

I am dealing with an API where It was a method on the Instance which returns a callback function

   myPlayer.onPlay(function() {
            console.log(this)
        })

Now I would expect the context of this to be the player but it is not it is the callback function. I have tried binding the context of this like this but it doesn't work either.

I expected this to be myPlayer as that is the context in which the onPlay function was executed?

myPlayer.onPlay(function() {
        console.log(this)
    }).bind(this)

How would I get the context to be the instance of the player? Am i missing something?

question from:https://stackoverflow.com/questions/65599727/the-context-of-this-in-a-callback-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would have to do

myPlayer.onPlay(
  function() {
    console.log(this);
  }.bind(myPlayer)
);

Since you haven't provided what .onPlay will return, I don't think it would return an object with a bind method. So you have to use bind on the function itself. You can't use this in the bind if you want it to be the myPlayer, because in your current call scope this doesn't mean something. It can mean something, but it most likely won't be the player, or else you would have done this.onPlay. You have to bind myPlayer with bind, not this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...