Search

7/04/2008

Peter's Blog - Module Pattern Provides No Privacy...at least not in JavaScript(TM)

Peter's Blog - Module Pattern Provides No Privacy...at least not in JavaScript(TM)

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.
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.


// 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

eval() in FF3 - just in case... - Google Caja Discuss | Google 網上論壇
Fortunately, all safe JavaScript subsets (Caja,
Cajita, ADsafe, FBJS, Jacaranda) already prevent access to the eval
function, as they must. So we should all be safe from this particular
new hole.

沒有留言: