2011/8/26 Xavier MONTILLET <[email protected]>:
> Here is how protected variables would work:
>
> ( function ( ) {
>
>    function XJSAccessors( object ) {
>        var undefined;
>        this.object = object;
>        var storage = this.storage = Object.create( object );
>        var getters = this.getters = { };
>        var setters = this.setters = { };
>
>        object.get = function ( name ) {
>            var getter = getters[ name ];
>            return getter === undefined ? storage[ name ] : getter(
> name, object );
>        };
>        object.set = function ( name, value ) {
>            var setter = setters[ name ];
>            return storage[ name ] = setter === undefined ? value :
> setter( value, name, object );
>        };
>        object.forIn = function( callback, that ) {
>            if ( argument.length < 2 ) {
>                that = this;
>            }
>            for ( var name in this ) {
>                callback.call( that, this.get( name ), name, this );
>            }
>        };
>    }
>
>    var XJSAccessorsPrototype = XJSAccessors.prototype;
>    function protectedSetter( value, name, object ) {
>        return object.get( name );
>    }
>    XJSAccessorsPrototype.protect = function ( name ) {
>        this.setters[ name ] = protectedSetter;
>    };
>
>    this.XJSAccessors = XJSAccessors;
> } )( );
>
> var o = { };
> var a = new XJSAccessors( o );
> console.log( o.set( 'p', 'v' ) );// 'v'
> a.protect( 'p' );
> console.log( o.set( 'p', 'WHATEVER' ) );;// 'v'

Why checking for undefined, why not check if it is in the object:
return name in getters ? getter( name, object ) : storage[ name ];

and

return name in setters ? setter( value, name, object ) : storage[ name
] = value;

-- 
Poetro

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to