简体   繁体   中英

Can you pass an objects method as a callback in JavaScript?

So I have an object lets call it A with a sub object which I'll call B which has a method/function called "CallMe" which I wish to be called when and object loads but I can't seem to get it to work. Is it even possible?

Example:

var A = {
  B: {
    CallMe: function() {
      alert('I\'ve been Called!');
    }
  }
}

var objImage = new Image();
objImage.onLoad = A.B.CallMe;
objImage.src = '/img/some_image.png';

您应该将其绑定到.onload属性而不是.onLoad这应该修复它,愚蠢的错字-这种情况最糟糕

It works fine... you just need to need to call it (objImage.onLoad();):

var A = {
  B: {
    CallMe: function() {
      alert('I\'ve been Called!');
    }
  }
}

var Image = function(){

}
Image.prototype.onLoad = null;

$(document).ready(function() {
    var objImage = new Image();
    objImage.onLoad = A.B.CallMe;

    objImage.onLoad();
});

Test code here: http://www.jsfiddle.net/yAJfd/1/

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