[JavaScript]宣告 Object / Closure

[JavaScript]宣告 Object / Closure

老實說JavaScript用很久了, 但一直很弱, 現在也還是,

最近看了一堆書, 好像懂了, 但又好像不懂, 經常語法寫錯或是undefine error,

跟學習java / c# 差很多, 總覺得always not my world,  只好慢慢累積程式碼 ...

 

範例是建立一個類似樹狀的物件,

    屬性:

        id: 此物件的識別項

        parent: 父物件

        child: 子物件

    方法:

        connect: 連結下一個物件. 參數 sub:  子物件

 

這是我比較熟的物件宣告:

 

   1:  // object demo
   2:              conn = function(id){
   3:                  var parent = [];
   4:                  var child = [];
   5:                  this.id = id;
   6:                  this.parent = parent;
   7:                  this.child = child;
   8:                  this.connect = function(sub){
   9:                      sub.parent.push(this);
  10:                      child.push(sub);
  11:                  };                
  12:              }
  13:   
  14:              var c1 = new conn("c1");
  15:              var c2 = new conn("c2");
  16:              c1.connect(c2);            
  17:              alert(c1.child[0].id + " " + c2.parent[0].id);

 

這是我試著熟悉的Closure宣告:

   1:  // closure
   2:              Conn = function(id){
   3:                  var parent = [];
   4:                  var child = [];
   5:                  return {
   6:                      id : id,
   7:                      parent : parent,
   8:                      child : child,
   9:                      connect : function(sub){
  10:                          sub.parent.push(this);
  11:                          child.push(sub);
  12:                      }
  13:                  };
  14:              }
  15:              
  16:              var c3 = Conn("c3");
  17:              var c4 = Conn("c4");
  18:              c3.connect(c4);            
  19:              alert(c3.child[0].id + " " + c4.parent[0].id);

 

ps. 在Closure每次回傳都是一個新的物件, 所以不需要new.

 

Fix to use the constructor array in 2011/11/21 reference http://james.padolsey.com/javascript/terse-javascript-101-part-1/

Thx for grence