Instantiating object in a function gives "Uncaught TypeError: undefined is not a function"

Instantiating object in a function gives "Uncaught TypeError: undefined is not a function"

我试图查看大多数关于我收到的错误消息的建议搜索结果,但不幸的是 none 正在谈论一个与我相似的案例。所以我相信这不是重复的。

(特别是我不用jQuery,我不想用。另外,给出的accepted answer是正确的,不涉及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);
     }
   }
 }
<canvas id='world'></canvas>


此代码无效。我在 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();
   }
 };


 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();
     }
   }
 }
<canvas id='world'></canvas>

问题出在这里:

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

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

您在 调用 drawGrid 之后分配 Cell 。所以,在 drawGridCell 里面是 undefined.

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

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

简单(更具可读性)修复 2:只需将调用移动到最后的 drawGrid