2011-04-25 47 views
1

我有以下的一段如我所料,其沒有運行代碼:嘗試使用MooTools的和拉斐爾

var person = new Class({ 
    initialize: function(name) 
    { 
     this.personName = name; 
     alert(this.personName)  //WORKS :-) 

     this.testFunc();    //WORKS :-) 
     this.createShape();   //PAINTS SHAPE BUT CANNOT ACCESS 'personName' 
    }, 
    testFunc() : function() 
    { 
     alert(this.personName); 
    }, 
    createShape() : function() 
    { 
     this.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"}); 
     $(this.personShape.node).click(function() 
     { 

      alert(this.personName); 
     }); 
    } 
}); 

click事件警報不工作,我也理解它的,因爲它不能訪問對象變量'personName'。不過,我想知道是否有可能以某種方式訪問​​它?

會有一個整潔的小javascript技巧來實現這個?

感謝您的任何反饋意見。

回答

1

createShapeclick函數中,上下文被設置爲this.personShape.nodethis不再指您的person,所以需要緩存。試試這個:

createShape: function() { 
    var context = this; 
    context.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"}); 
    $(context.personShape.node).click(function() { 
     alert(context.personName); 
    }); 
} 

此外,你的函數不應該在你的類/對象定義中有括號。另外,出於幾個原因,開始將大括號放在與陳述相同的行上是一個不錯的主意。這是我的重構:

var person = new Class({ 
    initialize: function(name) { 
     this.personName = name; 
     alert(this.personName)  //WORKS :-) 

     this.testFunc();    //WORKS :-) 
     this.createShape(); 
    }, 
    testFunc: function() { 
     alert(this.personName); 
    }, 
    createShape: function() { 
     var context = this; 
     context.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"}); 
     $(context.personShape.node).click(function() { 
      alert(context.personName); 
     }); 
    } 
}); 
+0

感謝一堆,這完美的工作。 – 2011-04-25 15:45:44