core.js:
var core = { all:{}, load: function(jsUrl) { $.ajaxStup({async, false}); $.getScript(jsUrl); }, init: function () { $.getJSON('someurl', function(data) { for(key in this.all) alert(key); }); }, here: function(who) { this.all[who.name] = who; } }; $(document).ready(function() { core.init(); });
me.js
(function() { core.here({name:"me", foo:"bar"}); })();
CASE 1:
<script type="text/javascript" src="/jquery.js"></script> <script type="text/javascript" src="/core.js"></script> <script type="text/javascript"> core.load("/me.js"); </script>
CASE 2:
<script type="text/javascript" src="/jquery.js"></script> <script type="text/javascript" src="/core.js"></script> <script type="text/javascript" src="/me.js"></script>
The problem is that for case 1 I get an alert, as I should , but for case 2, no alert…
So the question is: there is a load event for the <script>
tag? Qhat can I use to synchronize the files to work on case 2 (while debugging in IE8, I noticed that using a breakpoint solves the problem)? Is there anything I’m missing?
Advertisement
Answer
I am not sure why CASE 1 happened to work for you, but your problem seems to lie here:
$.getJSON('someurl', function(data) { alert(core === this); // <----- false, 'this' refers to the function's scope for(key in this.all) alert(key); });
“this” in javascript isn’t the same as “this” in C++ or Java
The problem is that function(data){...}
creates a closure (with a new this). So, inside that function, this
no longer refers to core
, it refers to the scope of the context from which it was called (somewhere inside jQuery in this case). You can fix it by protecting this
with a new variable, like so.
var self = this; $.getJSON('someurl', function(data) { for(var key in self.all){ alert(key); } });
This question can point you in the right direction for demystifying the this
keyword in javascript.