2011-08-03 28 views
0

にjQueryオブジェクトにリスナーを追加:ダウン機能のthis.ctxにしかしは、私は次のコードを持っているのコンストラクタ

<body> 
    <canvas id="canvas" height="300" width="300" style="border:1px solid" /> 
</body> 

<script> 
    function maze(canvas){ 
     this.ctx = canvas[0].getContext("2d"); 
     canvas.mousedown(down); 
    } 

    function down(e){ 
     alert(this.ctx); 
    }  
$(document).ready(function(e){ 
    var m = new maze($('#canvas')) 
}); 
</script> 

は未定義である、任意のアイデアなぜですか? (はい、jQuery 1.6.2をインポートしています)

答えて

1

ここでcanvasはjqueryオブジェクトを指しており、thisはmazeインスタンスを指します。だからこれを試してください

function maze(canvas){ 
     canvas.data("ctx", canvas[0].getContext("2d")); 
     canvas.mousedown(down); 
    } 

    function down(e){ 
     alert($(this).data("ctx")); 
    }  
$(document).ready(function(e){ 
    var m = new maze($('#canvas')) 
}); 
+0

更新された質問がこれを修正しましたが、まだthis.ctxの値を格納していません。 – Aly

+0

これは$(this)オブジェクトではなく、キャンバスのjqueryオブジェクトにデータを追加しますか? – Aly

+0

これは 'canvas' jqueryオブジェクトに追加されますが、' $(this) 'は' down'メソッドの同じキャンバスオブジェクトを指します。 – ShankarSangoli

関連する問題