var sayHello = function() { return 'Hello var'; }; function sayHello(name) { return 'Hello function'; }; sayHello();
> "Hello var"
为什么会这样,根据 StackOverFlow 的解释,实际上JavaScript的是按如下顺序解析的。
function sayHello(name) { return 'Hello function'; }; var sayHello = function() { return 'Hello var'; }; sayHello();
var NameSpace = window.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();
/* Object */ var NameSpace = window.NameSpace || {}; NameSpace.Hello = { name: 'world' , sayHello: function(_name) { return 'Hello ' + (_name || this.name); } };
NameSpace.Hello.sayHello('JS'); > Hello JS;
通过闭包(Closure)和Object实现
var NameSpace = window.NameSpace || {}; NameSpace.Hello = (function() { //待返回的公有对象 var self = {}; //私有变量或方法 var name = 'world'; //公有方法或变量 self.sayHello = function(_name) { return 'Hello ' + (_name || name); }; //返回的公有对象 return self; }());
var NameSpace = window.NameSpace || {}; NameSpace.Hello = (function() { var name = 'world'; var sayHello = function(_name) { return 'Hello ' + (_name || name); }; return { sayHello: sayHello }; }());
var NameSpace = window.NameSpace || {}; NameSpace.Hello = new function() { var self = this; var name = 'world'; self.sayHello = function(_name) { return 'Hello ' + (_name || name); }; };
调用
NameSpace.Hello.sayHello();
var yourNamespace = { foo: function() { }, bar: function() { } }; ... yourNamespace.foo();
转自:http://ourjs.com/detail/538d8d024929582e6200000c
© admin for 可乐吧, 2016. |
Permalink |
No comment |
Add to
del.icio.us
Post tags: 命名空间
Feed enhanced by Better Feed from Ozh