【发布时间】:2014-10-08 00:49:49
【问题描述】:
我似乎遇到了 JavaScript 中的名称间距问题。
我已将我的 javascript objects 分成单独的文件。
每个文件都以命名空间定义开始:
var MySystem = MySystem || {};
如果我包含对象,它会调用文件中包含的对象的某些方法 - 我收到 TypeError 说给定对象不存在。
我遇到的问题示例:
文件 1 Url.js(首先包含在 html 文档中):
var MySystem = MySystem || {};
MySystem.Url = {
objHelper : MySystem.Helper,
init : function() {
"use strict"
if (this.objHelper.isEmpty('string')) {
throw new Error('The string is empty');
}
}
}
文件 2 Helper.js(包含在 html 文档中的第二个):
var MySystem = MySystem || {};
MySystem.Helper = {
isEmpty : function(thisValue) {
"use strict"
return (
typeof thisValue === 'undefined' ||
thisValue === false ||
thisValue === null ||
thisValue === ''
);
}
}
当使用MySystem.Url.init(); 调用时,我得到:
TypeError: this.objHelper is undefined
if (this.objHelper.isEmpty('string')) {
当我颠倒包含文件的顺序时 - 一切正常。
这显然是一个非常简单的示例,但我的系统包含更多 objects - 它们都在自己的单独文件中。
解决此问题的最佳解决方法是什么?
【问题讨论】:
-
if (this.objHelper && this.objHelper.isEmpty('string'))? -
objHelper : MySystem.Helper只能在MySystem.Helper被先定义的情况下工作,只有当你颠倒文件的顺序时才会出现这种情况。 -
真的没有办法解决吗?我相信没有命名空间 - 只需使用直接对象就可以正常工作,但我喜欢组织的代码:(
-
为什么要使用
MySystem.Url.objHelper而不是简单的MySystem.Helper? -
因为它是一个单独的对象 - Url / Helper / Form / etc. Helper 也可能用于其他对象。
标签: javascript javascript-objects javascript-namespaces