pilavdzice
pilavdzice

Reputation: 958

javascript variable scope and requirejs modules

I have a durandal (basically requirejs) module that starts like this:

define(['plugins/http', 'durandal/app', 'knockout', 'plugins/ajax', 'plugins/formatters', 'durandal/global'], 
function (http, app, ko, ajax, formatters, global) {


//formatters is defined here
        var ctor = function () {

//formatters is not defined here

I put a breakpoint in the debugger and found that formatters is defined outside the function but inside the function it isn't...

Is this unique to requirejs modules? Usually variables declared outside the function can still be accessed in inner functions unless overridden. This seems like some kind of scope problem, but I don't understand what am I missing here - the inner function in within the scope of the outer one, so what's the problem?

Thanks!

Upvotes: 1

Views: 1433

Answers (2)

Kia Raad
Kia Raad

Reputation: 1335

I had this problem before and I managed to work around it by defining a varieble just after the function and assigning it the argument. E.g: Var fmtrs=formaters;

Upvotes: 1

Nathaniel Johnson
Nathaniel Johnson

Reputation: 4839

Your problem is likely not that the variable isn't available per se. Add a line like console.log(formatters) inside the ctor function

This will cause the closure to include the formatters variable and thus make it visible to the debugger. Closures only include variables if they are used - at least as far I have seen in Chrome and FF.

Upvotes: 3

Related Questions