Skip to content Skip to sidebar Skip to footer

How To Create Privacy With The Use Of Bind()

I pass an object literal into a framework method called supportP(). This object literal has a special property called _p which denotes that the members of it are private. From wi

Solution 1:

Will this work?

Yes, you will be able to access the "private" property via this._p.

Are there other things to consider?

You are cloning the object. Yet, the method on it has no access to it - it is bound to the "old" object whose properties will not reflect the changes on the copy. I am not sure whether this is by design or by accident.


For strict privateness, you will need to use closures with local variables. Properties can never be made private.

var singleton_object = (function() {
    var _p = 'I am private'; // local variablereturn {
        Name: 'test',
        publik_func: function () {
            // this will refer to this object so that it can access the properties// _p is accessible here due to closure, but not to anything else
        }
    };
}()); // immediately-executed function expression

Another solution, using two distinct objects (one hidden) which are passed into a framework method:

functionbindPrivates(private, obj) {
    for (var key in obj)
        if (typeof obj[key] == "function")
            obj[key] = obj[key].bind(obj, private);
    return obj;
}

var singleton_object = bindPrivates({
    p: 'I am private'
}, {
    Name: 'test',
    publik_func: function (_) {
        // this will refer to this object so that it can access "public" properties// _.p, a "private property" is accessible here due to binding the private //  object to the first argument
    }
});

Post a Comment for "How To Create Privacy With The Use Of Bind()"