需要将someObject.config.title
的值更新为click
事件中设置的值。我该怎么做呢?
还有一个单独的问题,有没有办法将$this
设置为可以通过该对象的任何子函数访问的全局变量?
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();
答案 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();