P
Peter Michaux
The module pattern has been discussed many times and has shown how
ECMAScript has the ability to encapsulate data as "private" variables
by using closures.
Today, in a comment on my blog, a reader, haysmark, points out that
Mozilla's JavaScript(TM), the implementation in Firefox, has a second
argument extension to eval that allows external code to spy on
otherwise private variables.
http://peter.michaux.ca/article/4947#comment-8061
Try the examples below in Firefox.
// Getting "private" variables
var obj = (function() {
var a = 21;
return {
// public function must reference 'a'
fn: function() {a;}
};
})();
var foo;
eval('foo=a', obj.fn);
console.log(foo); // 21
// Setting "private" variables
var obj = (function() {
var a = 21;
return {
getA: function(){return a;},
alertA: function(){alert(a);}
};
})();
console.log(obj.getA()); //21
eval('a=3', obj.getA);
console.log(obj.getA()); // 3
obj.alertA(); // 3
I don't think about the second argument to eval very frequently and
have never used it. This "hack" was a surprise to me and is a pretty
neat trick.
(I posted a slightly longer version of this message to my blog
http://peter.michaux.ca/article/8069 to try to see what others who
don't read this group think.)
Peter
ECMAScript has the ability to encapsulate data as "private" variables
by using closures.
Today, in a comment on my blog, a reader, haysmark, points out that
Mozilla's JavaScript(TM), the implementation in Firefox, has a second
argument extension to eval that allows external code to spy on
otherwise private variables.
http://peter.michaux.ca/article/4947#comment-8061
Try the examples below in Firefox.
// Getting "private" variables
var obj = (function() {
var a = 21;
return {
// public function must reference 'a'
fn: function() {a;}
};
})();
var foo;
eval('foo=a', obj.fn);
console.log(foo); // 21
// Setting "private" variables
var obj = (function() {
var a = 21;
return {
getA: function(){return a;},
alertA: function(){alert(a);}
};
})();
console.log(obj.getA()); //21
eval('a=3', obj.getA);
console.log(obj.getA()); // 3
obj.alertA(); // 3
I don't think about the second argument to eval very frequently and
have never used it. This "hack" was a surprise to me and is a pretty
neat trick.
(I posted a slightly longer version of this message to my blog
http://peter.michaux.ca/article/8069 to try to see what others who
don't read this group think.)
Peter