Javascript singleton private function is not accessing object properties when called from another method

StackOverflow https://stackoverflow.com/questions/23590510

Question

I have a simple singleton object and am having problems when a method calls another method that returns an object property.

var Customer = (function () {

var instance;

function init() {


    this.firstName = "";
    this.lastName = "";

    function _myGetFirstName() {
        return this.firstName;
    }

    function _myGetLastName() {
        return this.lastName;
    }

    function _myGetFullName() {
        return _myGetFirstName() + ' ' + _myGetLastName();
    }

    function _mySetFirstName(p) {
        this.firstName = p;
    }

    function _mySetLastName(p) {
        this.lastName = p;
    }

    return {

        setFirstName: _mySetFirstName,
        setLastName: _mySetLastName,
        getFirstName: _myGetFirstName,
        getLastName: _myGetLastName,
        getFullName: _myGetFullName,
    };

};

return {

    getInstance: function () {

        if (!instance) {
            instance = init();
        }

        return instance;
    }

};

})();

I'm using the object like this:

var cust = Customer.getInstance();
cust.setFirstName('FOO');
cust.setLastName('BAR');

console.log(cust.getFirstName());  // displays FOO - OK
console.log(cust.getLastName());   // displays BAR - OK
console.log(cust.getFullName());   // displays nothing

This is a pattern I've seen on the web multiple times, but I just can't get it to work. What am I doing wrong with the "_myGetFullName" method? When I get the individual first and last names, it works fine. Thanks

Was it helpful?

Solution

The instance you return is a new Object containing a few methods known to it. The local methods are not within the scope of instance. You should call the instance methods, so:

function _myGetFullName() {
        return this.getFirstName() + ' ' + this.getLastName();
}

or call the function within the context of the current instance

  function _myGetFullName() {
      return _myGetFirstName.call(instance) + ' ' + 
             _myGetLastName.call(instance);
  }

or, ofcourse

function _myGetFullName() {
        return this.firstName + ' ' + this.lastName;
}

Anyway, you code is a bit odd. You can only derive one instance of Customer. Didn't you mean something like this?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top