Literal
//object declaration with attribute and method var person = { //public attribute name:'', year:0, //public function Init:function(name, year){ this.name=name; this.year=year; } }
Module
//can declare private/public attribte and method var Person = (function(){ //private attribute var name; var privateInfo=function(){ return this.name; }; //All public method and attribute return{ //public attribute Nickname:'Andy', //public method getInfo:function(){ return Nickname + " - " + name; } } })();
目前看起來好像只有透過所謂Module的宣告方式才可以有public/private的特性,其他方式的的宣告方法看起來都沒有這個效果.
有鑑於有我第一次看到Module的宣告方式看了好久都看不懂,還以為是所謂的新語法,其實不是,帶我一一來拆解
//一般方法的宣告方式 var Person = function(){ /*do what you want*/ }; //execute method Person();
//如果方法裡面有回傳值 var Person = function(){ /*do what you want*/ // return a JSON object return{ pubVar:'', pubMethod:function() { // do method } } }; //execute the same method var obj = Person(); //get PubVar var val = obj.pubVar; //execute pubmethod obj.pubMethod();那如果宣告的同時就順便執行呢?
//用()把整個function的宣告包起來後順便再()執行 var person = (function(){ /*do what you want */ })(); //get PubVar var val = obj.pubVar; //execute pubmethod obj.pubMethod();
不曉得各位看官有沒有看懂了
沒有留言:
張貼留言