質問

Take the following function:

function createGlobalVar() {
y = "foo";
}

y //"foo"

in the absence of the keyword 'var', which would make y a local variable, the function climbs up the scope chain to try and find where y exists. Without any pre-existing declaration, it creates y as a global variable. Thus I don't need to add 'return y' at the end of my function in order for y to exist outside of it.

Now if I try to do the same thing, but assign a function expression to y, it won't work.

function createGlobalVar() {
y = function() { alert("foo!") }
}

y //"undefined"

I know how to correct it to make it work:

function createGlobalVar() {
y = function() { alert("foo!") }
return y;
}
var x = createGlobalVar();

x // function() { alert("foo!") }

But I don't understand WHY I have to return the global variable just because a functional expression was assigned to it. What's different?

役に立ちましたか?

解決

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).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top