From 0e232b4a2c2d9bfac5920022f74b953ccaf39fad Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Mon, 15 Nov 2010 23:22:24 -0500 Subject: [PATCH] Freezing class object after creation --- lib/class.js | 21 ++++++++++++++++++++- test/test-class.js | 10 +++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/lib/class.js b/lib/class.js index 55cca98..67c4bd9 100644 --- a/lib/class.js +++ b/lib/class.js @@ -22,12 +22,24 @@ * @package core */ -// whether getters/setters are supported +/** + * Whether getters/setters are supported + * @var {boolean} + */ var getset = ( Object.prototype.__defineGetter__ === undefined ) ? false : true ; +/** + * Whether the Object.freeze() method is available + * @var {boolean} + */ +var can_freeze = ( Object.seal === undefined ) + ? false + : true +; + /** * Creates a class, inheriting either from the provided base class or the @@ -133,6 +145,13 @@ var extend = ( function( extending ) new_class.prototype = prototype; new_class.constructor = new_class; + // lock down the new class (if supported) to ensure that we can't add + // members at runtime + if ( can_freeze ) + { + Object.freeze( new_class ); + } + // we're done with the extension process extending = false; diff --git a/test/test-class.js b/test/test-class.js index 5281122..1e29952 100644 --- a/test/test-class.js +++ b/test/test-class.js @@ -34,7 +34,10 @@ assert.ok( ); -var Foo = Class.extend(); +var Foo = Class.extend( +{ + value: 'foo', +}); assert.ok( @@ -42,3 +45,8 @@ assert.ok( "Extend method creates a new object" ); +assert.equal( + Object.isFrozen( Foo ), + true, + "Generated class should be frozen" +);