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
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 ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.