Geek scoping question.

48 views
Skip to first unread message

molipha

unread,
Oct 22, 2012, 7:57:27 PM10/22/12
to mootool...@googlegroups.com
Hi,

I'm reading Mark Obcena's Pro Javascript with mootools and have found some code that doesn't seem to agree with what he's written. When I run the following code in Firebug, I get myFn defined in all scopes. Any comments?

var myFn = function(){
// reference the function
console.log(typeof myFn);
};
myFn(); // 'function'

// global scope
var createFn = function(){
// result function
return function(){
console.log(typeof myFn);
};
};

// different scope
(function(){
// put the result function of `createFn`
// into a local variable
var myFn = createFn();
// check if reference is available
myFn(); // 'undefined' - NO! This shows up as defined!
})();

Arian Stolwijk

unread,
Oct 22, 2012, 8:24:45 PM10/22/12
to mootool...@googlegroups.com
Which page?

In the example you have it now (all the code together), the myFn() logs the type of the first myFn function in the global scope.
If you remove the typeof operator, you should see that it logs the first global myFn.

Basically what it does is:
define myFn and createFn in the global scope.
Create a new scope with the closure.
Define a new myFn in the closure.
Execute the global createFn. This changes the scope to the createFn scope.
lookup myFn. It's not in the createFn scope, so it looks it up in the createFn's parent scope: the global scope.
It finds the global myFn.

But anyway, I think Mark meant that you should execute the two cases separately.

molipha

unread,
Oct 24, 2012, 8:27:12 AM10/24/12
to mootool...@googlegroups.com
Hi,

The example starts on the bottom of page 15. Thanks for your analysis but actually the code works as I would expect. What confuses me is that Mark maintains that the last call to myFn() in the inline function should return 'undefined'. This is not correct, or I am doing something wrong.

Appreciate your input.

Arian Stolwijk

unread,
Oct 24, 2012, 8:39:50 AM10/24/12
to mootool...@googlegroups.com
Those are two separate examples, so you shouldn't execute them at the same time.
From page 29 a section about scoping starts, which explains this more.

molipha

unread,
Oct 27, 2012, 9:03:27 AM10/27/12
to mootool...@googlegroups.com
You are saying that since I ran them in firebug continuously, the variables were initialized for both functions. To run them as written, they would have to be in different pages. Got it. Thanks.


On Monday, October 22, 2012 9:57:27 PM UTC-2, molipha wrote:
Reply all
Reply to author
Forward
0 new messages