Private variables in inherited prototypes

后端 未结 4 1141
温柔的废话
温柔的废话 2020-12-05 00:54

I think I have misunderstood how Javascript prototypal inheritance works. Specifically, the prototypes internal variables seem to be shared between multiple different sub-ob

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 01:17

    The point of the prototype is that it is shared between multiple objects (i.e. those that are created by the same constructor function). If you need variables that are not shared between objects that share a prototype, you need to keep those variables within the constructor function for each object. Just use the prototype for sharing methods.

    In your example, you can't do exactly what you want using prototypes. Here's what you could do instead. See Daniel Earwicker's answer for more explanation that there's no point me now replicating here.

    var A = function() {};
    
    A.prototype.incrementPublic = function()
    {
        return ++this.publicProperty;
    };
    
    var B = function()
    {
        this.publicProperty = 0;
        var internal = 0;
        this.incrementInternal = function()
        {
          return ++internal;
        };
    };
    
    B.prototype = new A();
    
    var x = new B(), y = new B();
    console.log(x.incrementPublic(), y.incrementPublic()); // 1, 1
    console.log(x.incrementInternal(), y.incrementInternal()); // 1, 1
    

提交回复
热议问题