var self = this?

后端 未结 8 1402
失恋的感觉
失恋的感觉 2020-11-22 09:10

Using instance methods as callbacks for event handlers changes the scope of this from \"My instance\" to \"Whatever just called the callback\"

8条回答
  •  伪装坚强ぢ
    2020-11-22 09:31

    Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.

    It's something that took me a little while to really get, it does look odd at first.

    I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):

    function MyObject(){
      var me = this;
    
      //Events
      Click = onClick; //Allows user to override onClick event with their own
    
      //Event Handlers
      onClick = function(args){
        me.MyProperty = args; //Reference me, referencing this refers to onClick
        ...
        //Do other stuff
      }
    }
    

提交回复
热议问题