Closures inside specs

0 views
Skip to first unread message

Ruprict

unread,
Apr 14, 2010, 11:12:40 AM4/14/10
to jspec
Hi,

I have an object that looks something like:

function myObj(){

this.aFunc = function(){
this.property = new someLib.theirFunc();
};
}

I want to test the myObj.aFunc() function, but I don't want to pull in
the someLib code. I thought I could do with in the spec via a
closure, like so:

describe "aFunc()"
var objUnderTest= new myObj()
var someLib = {
theirFunc:function(){
return "hi";
}
}

objUnderTest.aFunc()

objUnderTest.property.should.be "hi"

end

However, the aFunc() does not see the closure, and and someLib is
null. Shouldn't this work?

(Be gentle...everytime I think I understand closures I run into a
situation where I am brutally shown how I don't)

Thanks.

pedz

unread,
Apr 17, 2010, 1:38:20 PM4/17/10
to jspec
Note to the next person -- be gentle with me too... this is what I
*think*...

What you describe is called dynamic scoping. At the time a variable
is referenced, the interpreter walks up the existing execution stack
looking for something with the same name. lisp is the classic
instance of a language that does dynamic scoping. i.e. what you would
work as you described if you were using lisp.

javascript does static scoping which means that at the time the code
is parsed, the connections between variable references and
declarations are made. To put this another way, a person can look at
the code and tell based upon the static scoping where a variable
reference is going to be resolved to.

closure is something else... it speaks more to when a variable is
going to be destroyed. In the non-closure, stack based method, when a
function returns, all the variables on the stack are destroyed. With
languages that use closure that is not necessarily the case. If a
reference still exists to the context, then it is not destroyed.

I've started writing code (based upon Crockford's lectures) like this:

function doodad() = {
var that = { };
var s = "howdy";
that.func = function () { print s; };
return that;
};

I create a doodad with:

d = doodad();

I can now call func with:

d.func();

At the time d.func is called, s still exists even though the call to
doodad has returned. In non-closure style languages (like C), the
compiler might let you do this but the reference to s would be so some
random piece of trash on the stack. With Javascript, the reference is
s is exactly what you think it should be.

But, the resolving of the reference to s is made at the time doodad is
parsed -- not when doodad is executed or when d.func is called.

--
JSpec thanks you for your interest and support! To post simply reply
to this email.

documentation: http://jspec.info
unsubscribe: jspec+un...@googlegroups.com
group: http://groups.google.com/group/jspec
Reply all
Reply to author
Forward
0 new messages