Lee Quarella
Lee Quarella

Reputation: 4742

'This' in phonegap

What is 'this' in phonegap? I am working on an app where I have local javascript packed with the app and remote javascript pulled from a server. I am using coffeescript to generate all the javascript.

Both files are being included in the app's index header, generated through haml as such:

%script{:src=>"javascripts/file1.js"}
%script{:src=>"http://192.168.5.205:3000/assets/file2.js"}

file1.js.coffee:

@myObj1 = property: true

file2.js.coffee:

@myObj2 = property: true

myObj1 is available globally and can be referenced as just myObj1, but myObj2 is only available via document.myObj2 and can not be referenced as simply myObj2. What is happening?

Upvotes: 3

Views: 995

Answers (1)

mu is too short
mu is too short

Reputation: 434785

Well, if you say this:

@myObj2 = property: true

and you have to reference myObj2 as document.myObj2 everywhere else, then this must be document when file2.js.coffee is executed. This sort of thing can happen if your code is executed through $(document).ready() or similar means (for example: http://jsfiddle.net/ambiguous/6DFK9/).

If you want something to be global, then you really should be explicit about it and use window:

# in file1.js.coffee:
window.myObj1 = property: true

# in file2.js.coffee:
window.myObj2 = property: true

That way you don't have to worry about the calling context and more importantly, your intent will be explicit and you won't have to puzzle over what this is or supposed to be in six months when you're trying to fix bugs. Say what you mean: if you want it global, put it in window.

Upvotes: 6

Related Questions