1.通过闭包(closure)和object实现
在闭包中声明好所有变量和方法,并通过一个json object返回公有接口:
var namespace = namespace || {}; namespace.hello = (function() { //待返回的公有对象 var self = {}; //私有变量或方法 var name = 'world'; //公有方法或变量 self.sayhello = function(_name) { return 'hello ' + (_name || name); } ; //返回的公有对象 return self; }());
2.通过json对象创建object,代码如下:
var namespace = namespace || {}; namespace.hello = { name: 'world' , sayhello: function(_name) { return 'hello ' + (_name || this.name); } };
3.通过函数(function)创建:(较为复杂)
这是一种比较常见的写法,通过声明一个function实现,函数里设置初始变量,公共方法写入prototype,如:
var namespace = namespace || {}; /* function */ namespace.hello = function() { this.name = 'world'; }; namespace.hello.prototype.sayhello = function(_name) { return 'hello ' + (_name || this.name); }; var hello = new namespace.hello(); hello.sayhello();
4.通过函数(function)创建:(较为简洁)
var namespace = namespace || {}; namespace.hello = new function() { var self = this; var name = 'world'; self.sayhello = function(_name) { return 'hello ' + (_name || name); }; };
推荐:《2021年js面试题及答案(大汇总)》
以上就是javascript创建命名空间的多种玩法的详细内容。
