简体   繁体   中英

using this keyword with javascript prototype addEventListener

I want to use this keyword in event listener function.

var MyViewModel = function (file) {
    this.status = "";

    this.xm = new XMLHttpRequest();    
    this.xm.addEventListener("load", this.onLoad, false);
};

MyViewModel.prototype.onLoad = function (e) {
    this.status = "ok";
};

I can not access the MyViewModel object with this keyword in onLoad prototype.

  • this object is window .
  • e parameter is XmlHttpRequest

How can I access this?

You can solve this problem with jQuery.proxy

This is specifying function scope.

var MyViewModel = function (file) {
    this.status = "";

    this.xm = new XMLHttpRequest();    
    this.xm.addEventListener("load",  $.proxy(this.onLoad, this), false);
};

MyViewModel.prototype.onLoad = function (e) {
    this.status = "ok";
};

Now you can use this keyword as MyViewModel.

Without jQuery you could also do something like:

function MyViewModel(file) {
    this.status = "";
    this.xm = new XMLHttpRequest();   
    var viewModel = this;
    this.xm.addEventListener("load", function(){viewModel.onLoad()}, false);
}

so that a reference to the instance is held in a closure using viewModel and then used to set this to the required value in the call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM