开发者

Javascript Object Function Scoping

开发者 https://www.devze.com 2023-01-27 22:50 出处:网络
Let\'s say I have a class: var as开发者_运维百科df = new Class({ myFunction: function () { //some stuff here

Let's say I have a class:

var as开发者_运维百科df = new Class({
  myFunction: function () {
    //some stuff here
  },
  anotherFunction: function() {
    globalObject.dosomethingandusecallback( 
      function() { // this is the callback
        //how do I call myFunction() here? I can't seem to get it to work?
      }
    );
  }
});

I seem to have some scoping problems in trying to call myFunction within the definition of my callback function. What am I missing here? I thought it should have access to myFunction in this context?

Thanks!


Copy the this keyword into a variable outside of the callback function, and use that variable inside the callback:

anotherFunction: function() {
  var self = this;
  globalObject.dosomethingandusecallback( 
    function() { // this is the callback
      self.myFunction();
    }
  );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消