从私有内部函数更新变量值

时间:2015-05-07 16:01:26

标签: javascript jquery

需要将someObject.config.title的值更新为click事件中设置的值。我该怎么做呢?

还有一个单独的问题,有没有办法将$this设置为可以通过该对象的任何子函数访问的全局变量?

jsFiddle

var someObject = {
    config: {
        title: ''
    },
    init: function() {
        // Any way to set $this as a global var that can accessed through any of the child functions of this object?
        var $this = this,
            title = $this.config.title;

        $('button').on( 'click' , function() {
            title = 'yo, waz gud son!';  
            // This reference works
            //$this.referenceTitle( title ); 
        });
         // This reference is undefined, need to update original value
        $this.referenceTitle( title ); 
    },
    referenceTitle: function(arg) {
        console.log( arg );
    }
}

someObject.init();

1 个答案:

答案 0 :(得分:2)

在您的代码中someObject.config不是私密的。

要使其成为私有变量(并获得对$this的引用),您可以执行以下操作:

var someObject = (function () {
    var config = {
        title: ''
    }; // config is now a private variable

    var $this = {
        init: function() {
            var title = config.title;

            $('button').on( 'click' , function() {
                title = 'yo, waz gud son!';  
                // This reference works
                //$this.referenceTitle( title ); 
            });
             // This reference is undefined, need to update original value
            $this.referenceTitle( title ); 
        },
        referenceTitle: function(arg) {
            console.log( arg );
        }
    };
    return $this;
}()); // <-- immediate invocation

someObject.init();