I am trying to have some const global variables which I can use in the javascript and I came out with this code and picking up from some answers referred in SO. But it seems that I have a little mistake somewhere which I couldn't spot. Can someone help me with this?
in testQuery.js
(function (window, undefined) {
var testQuery = function(obj) {
if (!(this instanceof testQuery)) {
return new testQuery(obj);
}
}
var MYGLOBALS = function() {
var globals = {
foo : "bar",
batz : "blah"
}
return {
getValue : function(s) {
return globals[s];
}
}
}();
window.testQuery = testQuery;
}) (window);
and in the html javascript tag i have this line of code.
in testQuery.html file
<html>
<head>
<script src="testQuery.js"></script>
<script>
function onClick() {
alert(MYGLOBALS.getValue("foo"));
}
</script>
</head>
<body>
<input type="button" onclick="onClick()">
</body>
</html>
I am trying to have some const global variables which I can use in the javascript and I came out with this code and picking up from some answers referred in SO. But it seems that I have a little mistake somewhere which I couldn't spot. Can someone help me with this?
in testQuery.js
(function (window, undefined) {
var testQuery = function(obj) {
if (!(this instanceof testQuery)) {
return new testQuery(obj);
}
}
var MYGLOBALS = function() {
var globals = {
foo : "bar",
batz : "blah"
}
return {
getValue : function(s) {
return globals[s];
}
}
}();
window.testQuery = testQuery;
}) (window);
and in the html javascript tag i have this line of code.
in testQuery.html file
<html>
<head>
<script src="testQuery.js"></script>
<script>
function onClick() {
alert(MYGLOBALS.getValue("foo"));
}
</script>
</head>
<body>
<input type="button" onclick="onClick()">
</body>
</html>
Share
Improve this question
edited Jun 20, 2011 at 16:20
T.J. Crowder
1.1m200 gold badges2k silver badges2k bronze badges
asked Jun 20, 2011 at 16:10
simplified.simplified.
211 silver badge3 bronze badges
4
- What makes you think you have a mistake? What error output/behaviour are you getting, and what did you expect? – Andrzej Doyle Commented Jun 20, 2011 at 16:12
- @Andrzej Doyle i am suppose to expect a pop up box that returns 'bar' from what i understand from the code. however, it seems that it is not responding to what i understand. – simplified. Commented Jun 20, 2011 at 16:13
- Part of the problem understanding it might have been that it was misleadingly (and inconsistently) indented. I've updated the indentation to be more standard, which may help (and will certainly help people reading the question). Edit: And now I've done it again (your edit wiped it out). – T.J. Crowder Commented Jun 20, 2011 at 16:18
- @T.J Crowder sorry about that, i was trying to add in the codes in the html file before i saw this ment. – simplified. Commented Jun 20, 2011 at 16:24
2 Answers
Reset to default 3The variable MYGLOBALS
is local to your scoping function (the big outermost function that has no name), so it can only be accessed from within that function.
I'm not sure what you mean by "...in the html javascript tag..." but if the alert
you've quoted is outside that scoping function, MYGLOBALS
is out of scope for it.
Update: The thing about JavaScript scope is that it's much simpler than people think it is. Variables declared with var
are private to the scope (function or global; JavaScript has no block-level scope so just {}
doesn't do it) in which they're declared, and sub-scopes of that scope (e.g., functions declared or define within it). And scope is entirely lexical — that is, it is what you see in the source code, not dictated by some other runtime structure. They don't pop out of that scope unless you see code somewhere explicitly making that happen, as with your window.testQuery = testQuery;
line, which explicitly makes testQuery
a property on window
and therefore a global variable. (And even then, it's not that the variable has popped out of the scope, just that you've created a new property referring to the same thing which is more broadly-accessible.)
Update 2: Re your ment
Actually what I am trying to do is to create something like what you would see when you are doing programming in other language where there will be a final static integer which you can put into the parameters fields on the functions you call. is there a better way of doing it? For example, in visual basic its something like me.background = Color.YELLOW. what I want is to have a static variable which will represent that YELLOW color.
JavaScript doesn't have user-defined constants, and doesn't have enums. (Update: Both of those things may change with ES6.) What you do instead is define an object with the properties, e.g.:
var COLORS = {
RED: "#FF0000",
BLUE: "#0000FF",
// ...
GREEN: "#00FF00"
};
Those aren't constants, there's nothing to keep anyone from assigning to COLORS.RED
except your telling them not to.
(Update: In ES5, we can make those properties constant using Object.defineProperties
, like this:
var COLORS = Object.defineProperties({}, {
RED: {value: "#FF0000"},
BLUE: {value: "#0000FF"},
// ...
GREEN: {value: "#00FF00"}
});
When you define a property that way, by default it's not writable.)
For what you're doing, you probably want the module pattern, where you have a single global symbol whose value is an object, and everything else is properties on that object:
(function() {
var mod;
// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = mod = {};
// Colors
mod.COLORS = {
RED: "#FF0000",
BLUE: "#0000FF",
// ...
GREEN: "#00FF00"
};
mod.testQuery = MyModule_testQuery;
function MyModule_testQuery() {
// Do something
}
})();
alert(MyModule.COLORS.RED); // #FF0000
MyModule.testQuery(); // Do something
Or if you prefer, that testQuery
function could be defined like this:
mod.testQuery = function() {
// Do something
};
...but then the function is anonymous, and I'm not a fan of anonymous functions. (Note that there's nothing special about the name MyModule_testQuery
, that's purely my naming convention.)
Somewhat off topic:
Regarding this line where we're publishing our global symbol above:
// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = mod = {};
Note that that is very specific to browser environments. We could make it applicable to any JavaScript environment with a trivial change:
// Create the global, and also give ourselves a convenient alias for it (`mod`)
this.MyModule = mod = {};
That works because we're the ones who call the outermost scoping function, and so we know that we're not calling it with any particular this
value (this
in JavaScript — unlike some other languages — is determined entirely by how a function is called, not where or how it's defined). So since we know we're not using any special this
value, we know that it will be the global object, because that's how JavaScript works. And the global object is window
on web browsers (effectively; technically window
is a property on the global object that refers back to itself).
http://jsfiddle/vXu7m/1/
Some syntactic cleanup, and attaching you MYGLOBALS to the window object should do what you want.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745365724a4624569.html
评论列表(0条)