我试图通过模块模式设置私有变量的值.所以我所说的是将$ content设置为我传递给person.content的值.但这似乎不起作用,因为当我对值进行警报时,它会给我一个未定义的错误.
$(document).ready(function(){
person.content = $('#content');
person.getContent();
});
// Person Module
var person = ( function(){
var $content;
function getContent(){
alert( 'content = '+$content.find(':first h2').text());
}
return {
content: $content,
getContent : getContent,
}
}( ) );
Run Code Online (Sandbox Code Playgroud)
你问的是,当你说这个时:
person.content = $('#content');
Run Code Online (Sandbox Code Playgroud)
你没有改变var $content;函数的内部,你只是改变了content属性的值person.然后,当你这样说:
person.getContent();
Run Code Online (Sandbox Code Playgroud)
内部getContent函数将使用var $content外部函数内的(未初始化的).你需要添加一个setContent功能:
var person = (function(){
var $content;
function setContent(c) {
$content = c;
}
// ...
return {
setContent: setContent,
getContent: getContent
};
}());
Run Code Online (Sandbox Code Playgroud)
并确保你不要在你的返回对象中留下那个尾随逗号,大多数(所有?)版本的IE都会对此感到不安.
然后,在其他地方:
person.setContent($('#content'));
person.getContent();
Run Code Online (Sandbox Code Playgroud)
根据您的目标浏览器和版本,您可以为返回对象的属性定义getter和setter函数:
但是使用显式的mutator函数将无处不在.