You forgot to call createGlobalVar
in your second example. There's no difference between assigning a function or a non-function expression to a property of a global object - and that's what happens when you write it like you did.
Note that using global object like this (unless you have very strong reasons) is discouraged. Have you wrote this function with the strict mode on, it would have thrown a ReferenceError on the line with y
:
function createGlobalVar() {
'use strict';
y = function() { alert("foo!") };
}
createGlobalVar();
>> ReferenceError: y is not defined
You can always turn the function into either a setter (assigning some value to its context object property) or a function in the old-school definition of the word (i.e. a snippet of code that actually returns some meaningful value).