Search code examples
javascriptinheritanceprivate-members

javascript private variable through inheritance


I'm stuck with a problem using javascript...
I want to declare a private variable in a class that can't be used from its sublclass...what I've tried is:

function Person(){
    var _name
    this.setName = function(name){
        _name = name
    }
    this.getName = function(){
        return _name
    }
}

function GreetingPerson(){
    var self = this;
    self.sayHello = function(){
        console.log(self.getName() + ': "Hello!"');
    }
}

GreetingPerson.prototype = new Person()
GreetingPerson.prototype.contructor = GreetingPerson;

var manuel = new GreetingPerson()
manuel.setName('Manuel');
manuel.sayHello();

var world = new GreetingPerson()
world.setName('World');
world.sayHello();
manuel.sayHello();
console.log(manuel.name)

In this way the name variable is private, but it is also static, so the last wo sayHello method calls, will write the same output.
I've tried also changing the Person class in this way:

function Person(){
    this.setName = function(name){
        this.name = name
    }
    this.getName = function(){
        return this.name
    }
}

But in this way it is not longer private.
What is the correct way to achieve it?


Solution

  • EDIT: Using something like @teddybeard says, you can get it too:

    function Person(){
        var _name;
        this.setName = function(name){
            _name = name;
        };
        this.getName = function(){
            return _name;
        };
      return this;
    }
    
    function GreetingPerson(){
        Person.call(this);
        this.sayHello = function(){
            console.log(this.getName() + ': "Hello!"');
        };
      return this;
    }
    
    GreetingPerson.prototype = new Person();
    GreetingPerson.prototype.constructor = GreetingPerson;
    
    var manuel = new GreetingPerson();
    manuel.setName('Manuel');
    manuel.sayHello();
    
    var world = new GreetingPerson();
    world.setName('World');
    world.sayHello();
    manuel.sayHello();
    console.log(manuel._name);
    

    But I'm not pretty sure if this is actually ok. The problem is that if you don't do something like Person.call(this); inside the constructor of GreetingPerson, you will not create a new instance of Person and it will always use the same _name value.