I am curious, why did you choose to use a factory instead of a constructor?Expand|Select|Wrap|Line Numbers
- function foo() {
- var privateVar = 42;
- var privateFunc = function() {
- alert(privateVar);
- };
- return {
- replacePF: function(f) { privateFunc = f; },
- accessPF: function() { privateFunc(); }
- };
- }
- var obj = foo();
It's a closure and `privateVar' in privateFunc() is bound to the executionExpand|Select|Wrap|Line Numbers
- obj.accessPF(); // 42
- obj.replacePF(function() {
- window.alert("The answer is "+privateVar);
- });
- obj.accessPF(); // privateVar is undefined
context of foo(), in which `privateFunc' was declared a variable. However,
the function expression in the obj.replacePF() call creates a closure in
which `privateVar' is bound to the execution context in which the call is
executed and the anonymous Function object is created, and in which scope
chain no object has such a property.
ISTM the only way to do this is to have a public method that returns
`privateVar', which would become "protected" through this: Either
Expand|Select|Wrap|Line Numbers
- function foo()
- {
- var privateVar = 42;
- var privateFunc = function() {
- window.alert(privateVar);
- };
- return {
- getPrivateVar: function() { return privateVar; },
- replacePF: function(f) { privateFunc = f; },
- accessPF: function() { privateFunc(); }
- };
- }
- var obj = foo();
Expand|Select|Wrap|Line Numbers
- function Foo()
- {
- var privateVar = 42;
- var privateFunc = function() {
- window.alert(privateVar);
- };
- this.getPrivateVar = function() { return privateVar; };
- this.replacePF = function(f) { privateFunc = f; };
- this.accessPF = function() { privateFunc(); };
- }
- var obj = new Foo();
- and then
- // 42
- obj.accessPF();
- obj.replacePF(function() {
- window.alert("The answer is " + obj.getPrivateVar());
- });
- // "The answer is 42"
- obj.accessPF();
HTH
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>