Javascript private member on prototype

前端 未结 8 947
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 01:15

Well I tried to figure out is this possible in any way. Here is code:

a=function(text)
{
   var b=text;
   if (!arguments.callee.prototype.get)
      argumen         


        
8条回答
  •  没有蜡笔的小新
    2020-12-08 01:57

    JavaScript traditionally did not provide a mechanism for property hiding ('private members').

    As JavaScript is lexically scoped, you could always simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.

    Of course, there are ways to work around this, but I wouldn't recommend it:

    Foo = (function() {
        var store = {}, guid = 0;
    
        function Foo() {
            this.__guid = ++guid;
            store[guid] = { bar : 'baz' };
        }
    
        Foo.prototype.getBar = function() {
            var privates = store[this.__guid];
            return privates.bar;
        };
    
        Foo.prototype.destroy = function() {
            delete store[this.__guid];
        };
    
        return Foo;
    })();
    

    This will store the 'private' properties in another object seperate from your Foo instance. Make sure to call destroy() after you're done wih the object: otherwise, you've just created a memory leak.


    edit 2015-12-01: ECMAScript6 makes improved variants that do not require manual object destruction possible, eg by using a WeakMap or preferably a Symbol, avoiding the need for an external store altogether:

    var Foo = (function() {
        var bar = Symbol('bar');
    
        function Foo() {
            this[bar] = 'baz';
        }
    
        Foo.prototype.getBar = function() {
            return this[bar];
        };
    
        return Foo;
    })();
    

提交回复
热议问题