How to deal with Uncaught TypeError?
-
/*
Dear all,<!-- code -->
<script>
function Array2D(x,y){
this.length = x*y;
this.x = x;
this.y = y;for(var i=0 ; i<this.length ; i++){ this\[i\] = null; } this.get = function(x,y){ return this\[x\*this.x+y\]; } this.set = function(x,y,value){ this\[x\*this.x+y\] = value; } }
</script>
<script>
var a2d = Array2D(10,10);
a2d.set(2,3,"2");
alert(this.get(1,2));
</script>
<!-- end code --><!-- error message -->
Uncaught TypeError: Cannot read property 'set' of undefinedHow does it happen?and what should i do to avoid this?
*/ -
/*
Dear all,<!-- code -->
<script>
function Array2D(x,y){
this.length = x*y;
this.x = x;
this.y = y;for(var i=0 ; i<this.length ; i++){ this\[i\] = null; } this.get = function(x,y){ return this\[x\*this.x+y\]; } this.set = function(x,y,value){ this\[x\*this.x+y\] = value; } }
</script>
<script>
var a2d = Array2D(10,10);
a2d.set(2,3,"2");
alert(this.get(1,2));
</script>
<!-- end code --><!-- error message -->
Uncaught TypeError: Cannot read property 'set' of undefinedHow does it happen?and what should i do to avoid this?
*/It's undefined because you ahven't returned anything form your Array2D function. Try adding
return this;
at the end of it. Also, your
alert(this.get(1,2));
shouold be
alert(a2d.get(1,2));
-
It's undefined because you ahven't returned anything form your Array2D function. Try adding
return this;
at the end of it. Also, your
alert(this.get(1,2));
shouold be
alert(a2d.get(1,2));