i have 2 functions same name, thought localized not sure not understanding here, seems 1 of functions isn't created or something.
i have code setup - starts bottom line:
function getdiv(id) { return document.getelementbyid(id); } var account = new function(){ this.load = function(){ //load user data server elements } this.init = function(){ this.load(); //error : this.load not function } } var template = new function(){ this.addevents = function(){ var el = getdiv('output'); el.addeventlistener('mousedown',account.init,false); } this.load = function(){ //load template page this.addevents(); } this.init = function(){ this.load(); } } template.init(); //start of script: load template i hope makes reasonable sense in following code goes not understanding why in account.init error, template.init not - pretty similar setup.
what causing , how solve ?
when creating event listener el.addeventlistener('mousedown',account.init,false);, element el becomes scope of account.init , that's this refer to. avoid it, save reference this closure.
var account = new function(){ var self = this; this.load = function(){ //load user data server elements } this.init = function(){ self.load(); // "this" in "account" accessible here through closure "self" } } info on this , closures https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/this
Comments
Post a Comment