Pseudo-protected properties

A little test to see how to best limit the accessibility of a property to a predefined scope, i.e. function. Unfortunately uses arguments.callee.caller.

by Derija93

HTML

<button>Start!</button>

JavaScript

/**
 * Needs serious up-dating! arguments.callee is deprecated in
 * ECMAScript5 and so is Function.caller.
 * I tried a stack trace, but that didn't work out reliably or well
 * at all.
 */

(function myScope( ) {
    window.Test = function ( string ) {
        var _string = string;
        
        Object.defineProperty(this, 'string', {
            get : function( ) {
                return _string;
            },
            set : function( value ) {
                var currCaller = arguments.callee.caller;
                while( currCaller ) {
                    if( currCaller == myScope ) {
                        _string = value;
                        return;
                    }
                    currCaller = currCaller.caller;
                }
            }
        });
    };
    
    var test = new Test('Test');
    console.log(test.string = 'Test 2');
}());

(function autostart( ) {
    $('button').click(function( jqEvt ) {
        var foo = new Test('foo');
        foo.string = 'bar';
        console.log(foo.string);
    });
}());