【发布时间】:2012-08-31 15:04:47
【问题描述】:
如何访问命名空间中的对象。 1) 我有一个导入脚本文件的 html
一个脚本定义命名空间应用程序,另一个脚本将一个对象附加到它
我如何访问对象并开始使用它
app.js
var app = (function(jQuery){
if (!jQuery) {
alert(app.resources["MISSING_LIB"]);
return null;
}
return {
init: function() {
//code for init the app related variables and subnamspaces
}
};
})(jQuery);
jQuery(document).ready(function(){
app.init();
});
personal.js
function(app){
if (app) {
app.Cache = function(nativeStorage,serializer ) {
this.storage = nativeStorage;
this.serializer = serializer;
}
app.Cache.prototype = {
setItem: function( key, value ){
this.storage.setItem(key, this.serializer.stringify( value ));
return( this );
}
};
var personalcontentstorage = new app.Cache(localStorage,JSON);
} else {
alert("app is undefined!");
}
})(app);
myhtml.html
<html>
<head>
<script src="${ '/js/app.js'" type="text/javascript"></script>
<script src="${ '/js/personal.js'" type="text/javascript"></script>
</head>
<body>
<h1>
Exploring HTML5's localStorage
</h1>
<script type="text/javascript">
jQuery(document).ready(function(){
personalcontentstorage.setItem("mykey","myValue") ;
});
</script>
</body>
</html>
如何访问对象“personalcontentstorage”以便我可以使用它的方法。访问 hte 对象时出现未定义的错误。我无法按照上面写的方式访问对象
【问题讨论】:
-
init: function() {在您的 app.js 定义中是一个语法错误。检查你的控制台。 -
我放在这里供考虑的代码是伪代码,我原来的 app.js 是一个巨大的文件,它工作正常。我希望使用personal.js中定义的对象的方法可以在html的dom中使用
-
感谢大家的反馈,作为一名 Java 开发人员,试图在一个快节奏的项目中理解 JS 的糟糕之处,您的反馈确实帮助我正确理解了 JS 的概念 :)
标签: javascript javascript-namespaces