在函数中实例化对象会给出" Uncaught TypeError:undefined不是函数"

时间:2015-07-06 13:45:17

标签: javascript undefined hoisting

我试图查看有关我收到的错误消息的大部分建议搜索结果,但不幸的是没有人在讨论与我类似的案例。所以我认为这不是重复。

(特别是我不使用jQuery,我不想使用它。此外,接受的答案是正确的,它不涉及jQuery,它详细阐述了对吊装的理解在JavaScript中。)

我想知道为什么下面的代码(第二个代码段)不起作用?我无法解决这个问题。

此代码有效。我在drawGrid函数之外实例化Cell对象。



 'use strict';

 var dim = 20;
 var side_length = 25;

 var canvas = document.getElementById('world');
 canvas.width = 500;
 canvas.height = 500;
 document.body.appendChild(canvas);

 if (canvas.getContext) {
   var ctx = canvas.getContext('2d');
   drawGrid(ctx);
 }

 var Cell = function(x, y, alive, context) {
   this.x = x;
   this.y = y;
   this.alive = alive;
   this.ctx = context;
 };

 Cell.prototype.draw = function() {
   if (this.alive === true) {
     this.ctx.beginPath();
     this.ctx.arc(this.x + side_length / 2, this.y + side_length / 2, 10, 0, 2 * Math.PI);
     this.ctx.fill();
   }
 };

 for (var i = 0; i < dim; i++) {
   for (var j = 0; j < dim; j++) {
     var x = i * canvas.width / dim,
       y = j * canvas.height / dim;
     new Cell(x, y, true, ctx).draw();
   }
 }

 function drawGrid(ctx) {
   for (var i = 0; i < dim; i++) {
     for (var j = 0; j < dim; j++) {
       var x = i * canvas.width / dim,
         y = j * canvas.height / dim;
       ctx.strokeRect(x, y, side_length, side_length);
     }
   }
 }
&#13;
<canvas id='world'></canvas>
&#13;
&#13;
&#13;

此代码不起作用。我在drawGrid函数中实例化Cell对象。

&#13;
&#13;
 'use strict';

 var dim = 20;
 var side_length = 25;

 var canvas = document.getElementById('world');
 canvas.width = 500;
 canvas.height = 500;
 document.body.appendChild(canvas);

 if (canvas.getContext) {
   var ctx = canvas.getContext('2d');
   drawGrid(ctx);
 }

 var Cell = function(x, y, alive, context) {
   this.x = x;
   this.y = y;
   this.alive = alive;
   this.ctx = context;
 };

 Cell.prototype.draw = function() {
   if (this.alive === true) {
     this.ctx.beginPath();
     this.ctx.arc(this.x + side_length / 2, this.y + side_length / 2, 10, 0, 2 * Math.PI);
     this.ctx.fill();
   }
 };


 function drawGrid(ctx) {
   for (var i = 0; i < dim; i++) {
     for (var j = 0; j < dim; j++) {
       var x = i * canvas.width / dim,
         y = j * canvas.height / dim;
       ctx.strokeRect(x, y, side_length, side_length);
       new Cell(x, y, true, ctx).draw();
     }
   }
 }
&#13;
<canvas id='world'></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

问题在于:

 if (canvas.getContext) {
   var ctx = canvas.getContext('2d');
   drawGrid(ctx);
 }

 var Cell = function(x, y, alive, context) {

您在致电Cell后分配drawGrid 。因此,在drawGrid内,Cellundefined

简单修复1,使用标准函数声明在变量声明中赋值hoisted

 function Cell(x, y, alive, context) {

简单(更具可读性)修复2:只需将呼叫移至最后的drawGrid