I tried to ask this in a different question but did a poor job of it. This first block of code is from a JS example in David Flanagan's book. The main point of the example is that after getCounter()
returns, the scope that is shared by the methods next
and reset
is private and no longer accessible by the rest of the code. In other words, n
cannot be changed except through the two methods.
The second block of code is from an example from John Ousterhout's book on Tcl and refers to namespaces. I am not implying that his example had to do with scope; I'd just like to know if it can be made to do so. It works about the same as the JS example, as far as having the procedures change the value of num
, but the scope is not private. The outer code can simply set counter::num 10
which cannot be done in the JS example. At least there appears no way to access n
.
My question is is there a way to make the scope private in Tcl as in the JS example, apart from using an OOP Tcl library?
Thank you.
"use strict";
function getCounter () {
var n = 0;
return {
next: function () { return ++n; },
reset: function () { n = 0; }
};
}
var counter = getCounter();
console.log(counter.next()); // 1
console.log(counter.next()); // 2
console.log(counter.next()); // 3
counter.reset();
console.log(counter.next()); // 1
console.log(counter.next()); // 2
console.log(counter.next()); // 3
// Cannot access n from here because
// private scope.
namespace eval counter {
variable num 0
proc next {} {
variable num
return [incr num]
}
proc reset {} {
variable num
set num 0
}
}
chan puts [counter::next]; # 1
chan puts [counter::next]; # 2
chan puts [counter::next]; # 3
counter::reset
chan puts [counter::next]; # 1
chan puts [counter::next]; # 2
chan puts [counter::next]; # 3
set counter::num 10
chan puts [counter::next]; # 11
chan puts [counter::next]; # 12