Javascript Scope and this.Variable -
so have javascript next (pseudo) structure. how set this.last_updated
variable of parent function showupdates
function, without referencing name assignment (my_main_function
).
var my_main_function = new main() function main() { this.last_updated; function showupdates(data){ //set this.last_updated= // stuff } this.updatemain(){ $.ajax({ url:"/my_url/" type:"post", datatype:"json", data: {'last_updated':this.last_updated }, success : function(data) { showupdates(data)}, error : function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responsetext); }, }); } }
updated code base of operations 1 comments:
there 2 way of creating objects.
if need create object multiple time this:
var yourdefintinon = function() { }; yourdefintinon.prototype.foo = function() { }; obj1 = new yourdefintinon(); obj2 = new yourdefintinon(); obj1.foo();
if need 1 time in code can that:
var obj = { }; obj.foo = function() { }; foo();
so need main
1 time code this: using function.prototype.bind (and polyfill older browsers) bind showupdates
obj
.
var main = { last_updated : null }; function showupdates(data){ this.last_updated = data.update_time; } main.updatemain = function () { //<< bind showupdates `this` , save bound function in local variabel showupdates var showupdates = showupdates.bind(this); $.ajax({ url:"/my_url/" type:"post", datatype:"json", data: {'last_updated':last_updated }, success : showupdates, //<< uses showupdates variable not function error : function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responsetext); }, }); };
as don't want create showupdates
accessible others wrap whole block function immediatly called:
var main = (function() { var main = { last_updated : null }; function showupdates(data){ this.last_updated = data.update_time; } main.updatemain = function () { var showupdates = showupdates.bind(this); $.ajax({ url:"/my_url/" type:"post", datatype:"json", data: {'last_updated':last_updated }, success : showupdates, error : function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responsetext); }, }); }; homecoming main; }());
javascript scope
No comments:
Post a Comment