Last active
August 29, 2015 14:04
-
-
Save marsen/e85a15fd5e366487ff5b to your computer and use it in GitHub Desktop.
About javascript Module Pattern Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<meta charset="utf-8" /> | |
<title></title> | |
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> | |
<script type="text/javascript"> | |
//#region | |
var MyModule = {}; | |
MyModule.namespace = function (ns_string) { | |
var parts = ns_string.split('.'), | |
parent = MyModule, | |
count, | |
i; | |
if (parts[0] === "MyModule") { | |
parts = parts.slice(1); | |
} | |
count = parts.length; | |
for (i = 0 ; i < count; i += 1) { | |
if (typeof parent[parts[i]] === "undefined") { | |
parent[parts[i]] = {}; | |
} | |
parent = parent[parts[i]]; | |
} | |
return parent; | |
}; | |
MyModule.namespace('MyModule.Marsen.Temp'); | |
//#endregion | |
MyModule.Marsen.Temp = (function (app,global) { | |
var Constructor; | |
//這是一個私有變數 | |
var aboutMe = { | |
version: "Beta 1.01", | |
writer: "Marsen Lin", | |
license: "MIT" | |
}; | |
Constructor = function () { | |
var name = "Guest"; | |
this.About= function () { console.log("Version:" + aboutMe.version + ";Writed by" + aboutMe.writer + ";License" + aboutMe.license) }, | |
this.Version = function (){return aboutMe.version;},//只揭露必要的資訊 | |
this.SayHi= function (_name) { | |
if (_name) { | |
name = _name; | |
console.log("Hello," + name + "! I remember your name ."); | |
} else { | |
console.log("Hello," + name + "! I dont know your name ."); | |
} | |
} | |
}; | |
Constructor.prototype = (function () { | |
var info = "Hello , this is a javascript Module, I hope you love it"; | |
return { | |
Info: info | |
}; | |
}()); | |
return Constructor; | |
}(MyModule,this));//立即函式建立模組,引進全域變數 | |
$(function () { | |
//new 出模組物件,並執行其方法 | |
var mark = new MyModule.Marsen.Temp(); | |
mark.SayHi("Mark"); | |
var anonymous = new MyModule.Marsen.Temp(); | |
anonymous.SayHi(); | |
}); | |
</script> | |
</head> | |
<body> | |
<input type="button" value="Create Module"> | |
<div style="display:none;"> | |
<script type="text/template" id="dialogBox"> | |
</script> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment