如何在JavaScript中创建命名空间,使我的对象和函数不被其他同名对象和函数覆盖?我使用了以下方法:
if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}
有没有更优雅或更简洁的方式来做到这一点?
如何在JavaScript中创建命名空间,使我的对象和函数不被其他同名对象和函数覆盖?我使用了以下方法:
if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}
有没有更优雅或更简洁的方式来做到这一点?
当前回答
我认为对于这样一个简单的问题,你们都使用了太多的代码。 没必要为它回购。 这是一个单线函数。
namespace => namespace.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);
试试吧:
//——定义—— Const namespace = name => name.split(".")。减少(下)(最后,= >(去年[下]=(去年[下一个 ] || {})), 窗口); //——使用---- Const c =命名空间("a.b.c"); c.MyClass = class MyClass {}; //—参见---- Console.log ("a: ", a);
其他回答
我通常在闭包中构建它:
var MYNS = MYNS || {};
MYNS.subns = (function() {
function privateMethod() {
// Do private stuff, or build internal.
return "Message";
}
return {
someProperty: 'prop value',
publicMethod: function() {
return privateMethod() + " stuff";
}
};
})();
自从写了这篇文章以来,我的风格在这些年里有了微妙的变化,现在我发现自己是这样写闭包的:
var MYNS = MYNS || {};
MYNS.subns = (function() {
var internalState = "Message";
var privateMethod = function() {
// Do private stuff, or build internal.
return internalState;
};
var publicMethod = function() {
return privateMethod() + " stuff";
};
return {
someProperty: 'prop value',
publicMethod: publicMethod
};
})();
通过这种方式,我发现公共API和实现更容易理解。将return语句视为实现的公共接口。
如果使用Makefile,您可以这样做。
// prelude.hjs
billy = new (
function moduleWrapper () {
const exports = this;
// postlude.hjs
return exports;
})();
// someinternalfile.js
function bob () { console.log('hi'); }
exports.bob = bob;
// clientfile.js
billy.bob();
当我写到1000行左右时,我更喜欢使用Makefile,因为我可以通过删除Makefile中的一行来有效地注释掉大量代码。这样就很容易摆弄东西了。此外,使用这种技术,名称空间只在开头出现一次,因此很容易更改,并且不必在库代码中不断重复它。
当使用makefile时,在浏览器中进行实时开发的shell脚本:
while (true); do make; sleep 1; done
将此添加为make任务“go”,您可以“make go”以在编写代码时保持构建的更新。
我创建的命名空间是受到Erlang模块的启发。这是一种非常实用的方法,但这就是我最近编写JavaScript代码的方式。
它为闭包提供全局名称空间,并在闭包中公开已定义的集合函数。
(function(){
namespace("images", previous, next);
// ^^ This creates or finds a root object, images, and binds the two functions to it.
// It works even though those functions are not yet defined.
function previous(){ ... }
function next(){ ... }
function find(){ ... } // A private function
})();
示例:
var namespace = {};
namespace.module1 = (function(){
var self = {};
self.initialized = false;
self.init = function(){
setTimeout(self.onTimeout, 1000)
};
self.onTimeout = function(){
alert('onTimeout')
self.initialized = true;
};
self.init(); /* If it needs to auto-initialize, */
/* You can also call 'namespace.module1.init();' from outside the module. */
return self;
})()
你可以声明一个局部变量,就像self和assign local。onTimeout如果你想要它是私有的。
我的习惯是使用函数myName()作为属性存储,然后var myName作为“方法”持有者…
不管这是否合法,打我吧!我一直依赖于我的PHP逻辑,事情很简单。: D
function myObj() {
this.prop1 = 1;
this.prop2 = 2;
this.prop3 = 'string';
}
var myObj = (
(myObj instanceof Function !== false)
? Object.create({
$props: new myObj(),
fName1: function() { /* code.. */ },
fName2: function() { /* code ...*/ }
})
: console.log('Object creation failed!')
);
if (this !== that) myObj.fName1();其他myObj.fName2 ();
你也可以用“反之亦然”的方式在对象创建之前进行检查,这样更好:
function myObj() {
this.prop1 = 1;
this.prop2 = 2;
this.prop3 = 'string';
}
var myObj = (
(typeof(myObj) !== "function" || myObj instanceof Function === false)
? new Boolean()
: Object.create({
$props: new myObj(),
init: function () { return; },
fName1: function() { /* code.. */ },
fName2: function() { /* code ...*/ }
})
);
if (myObj instanceof Boolean) {
Object.freeze(myObj);
console.log('myObj failed!');
debugger;
}
else
myObj.init();
JavaScript:使用Object.create()创建对象