我想在c#
中写一行namespace abc.def.ghi{
get1();
get2();
get3();
get4();
}
减少我在
这么多行中的文字abc.def.ghi.get1();
abc.def.ghi.get2();
abc.def.ghi.get3();
abc.def.ghi.get4();
可以在javascript中使用吗?
答案 0 :(得分:3)
对象。无论如何我学到的方式
var abc = {};
abc.def = {};
abc.def.ghi = {};
abc.def.ghi.get1 = function(){};
abc.def.ghi.get2 = function(){};
abc.def.ghi.get3 = function(){};
abc.def.ghi.get4 = function(){};
修改强>
可能误解了这个问题。如果您想减少所需的打字数量,请使用
var ns = abc.def.ghi;
ns.get1();
等
答案 1 :(得分:1)
这可以通过一些自定义代码实现:
首先定义命名空间函数和命名对象函数,如下所示:
var jaf = {}; // define a top level global object for your library
/**
* Creates a named Object with a <tt>name</tt> field which is assigned the
* <tt>strName</tt> and a toString method
* @private
* @param {String} strName The name of the named object
*/
function namedObject(strName) {
return {
name: strName,
toString: function() {
return this.name;
}
};
}
/**
* Createa new namespace(s) globally or returns existing ones if already created. Namespaces
* can be used to avoid creating a lot of global objects and structuring a project's
* modules and classes. Namespaces are like packages in java. The namespace is a
* simple string or a dot separated string of characters that are allowed in identifiers
* e.g. "jaf.core" is a valid namespace but "jaf.1" is not.
* @param {String} strNs The namespace string
* @return {Object} The namespace object
*/
var namespace = function(strNs) {
var arrNsc = strNs.split(".");
var nsObj = null;
var i = 0;
var len = arrNsc.length;
var nsName = "";
if(arrNsc[0] === "jaf") {
nsObj = jaf;
i = 1;
nsName = "jaf.";
}
for(; i < len; i++) {
var ns = arrNsc[i];
nsName += (ns + ".");
if(!nsObj) {
if(!window[ns]) {
nsObj = window[ns] = namedObject(nsName.substring(0, nsName.length - 1));
}else {
nsObj = window[ns];
}
}else {
if(!nsObj[ns]) {
nsObj = nsObj[ns] = namedObject(nsName.substring(0, nsName.length - 1));
}else {
nsObj = nsObj[ns];
}
}
}
return nsObj;
}
然后你可以这样做:
var ns = namespace("jaf.core.util");
ns.MyUtil = function() {
// do something important
}
如果将变量“jaf”更改为全局对象,请确保使用适当的变量更改命名空间函数。但你仍然可以做类似的事情:
var ns1 = namespace("abc.def.ghi")
ns1.get1() = function() {}
ns1.get2() = function() {}
ns1.get3() = function() {}
它仍然会以这种方式运作。
答案 2 :(得分:0)