One difference between Smalltalk and Javascript that might surprise people is how they deal with "return" from within a closure. In Javascript, the return from a closure returns to the method that evaluated the closure. In Smalltalk, the return from a closure returns from the stack frame where the closure was created. I'll illustrate this a little better example:
function topMethod() {
return childMethod( function() { return 1 } );
}
function childMethod(closure) {
return closure() + 1;
}
topMethod(); /* returns 2 */
In the above example, the closure is created in topMethod, but evaluated in childMethod. The return from the closure of 1 returns to childMethod where it is evaluated.
topMethod
^self childMethod: [^1]
childMethod: aClosure
^aClosure value + 1
self topMethod "returns 1"
Where-as, in the Smalltalk example, the closure returns back to topMethod, not back to childMethod. This may be a little surprising to any Javascript programmers out there, except that there is an alternative path here in Smalltalk:
topMethod
^self childMethod: [1]
childMethod: aClosure
^aClosure value + 1
self topMethod "returns 2"
As we can see in this variant, the closure does not explicitly do a return - it has an implicit return value, which is the value of the last statement in the closure. This can be counter-intuitive to the uninitiated. In fact, it's so odd that I saw the following question roll by today in the IRC channel:
How do I return from a closure back to the method that evaluated it
Actually, it wasn't asked in those words. There was some confusion added in to the mix, because if you're in Squeak you have a way to do this already:
topMethod
^self childMethod: [thisContext return: 1]
childMethod: aClosure
^aClosure value + 1
self topMethod "returns 2"
But in VisualWorks, the only return semantics we have are to do the equivalent of ^. So I wondered, what would it take to implement a version that does the same as Squeak's #return: ?
BlockContext>>blockReturn: aValue
self unwindUpTo: sender.
sender == nil ifTrue: [^self cannotReturn: aValue].
sender resumeWith: aValue.
^sender
This gives us the same ability as in Squeak, where we can now write the cold thisContext blockReturn: 1 and it will unwind the stack back to the sender, then resume the sender with the desired return value.
This kind of semantic control is sometimes useful where a closure has become a bit of a case statement and you desire to leave the block early rather than branch it with lots of ifTrue:ifFalse: calls.
Of course, the usual pat on Smalltalk's back is required here - we've just done some very simple stack manipulation, extended a kernel class and all without breaking a sweat to give ourselves a completely new control structure.