简体   繁体   English

从另一个方法调用时,Javascript单例私有函数不访问对象属性

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

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? “ _myGetFullName”方法在做什么? 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. 您返回的instance是一个新的Object其中包含一些已知的方法。 The local methods are not within the scope of instance . 本地方法不在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 或在当前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. 您只能派生一个Customer实例。 Didn't you mean something like this ? 没有你的意思是这样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM