标签:
var sayHello = function() { return ‘Hello var‘; }; function sayHello(name) { return ‘Hello function‘; }; sayHello();
> "Hello var"
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();
标签:
原文地址:http://www.cnblogs.com/Dylanblogs/p/4893894.html