Javascript - 在未定义的对象上调用 new

Javascript - call new on undefined object

本文关键字:调用 new 对象 未定义 Javascript      更新时间:2023-09-26

我正在使用require.js来组织我的js:

define([
   'underscore',
   'sylvester',
   'glUtils',
   'GLFacade',
   'Item',
   'Attribute',
   'Buffer',
], function(
   _,
   sylv,
   glUtils,
   GLFacade,
   Item,
   Attribute,
   Buffer
) {
   "use strict";
   function Sprite() { this.init.apply(this, arguments); }
   _.extend(Sprite.prototype, {
      init: function(prog, img, viewPort) {
         this._frameNum = 0;
         this._framesPerAnimation = 4;
         this._prog = prog;
         this._viewPort = viewPort;
         this._img = new ImageWrapper(img);
         //...other initialization stuff...
      },
      //...other methods...
   });
   return Sprite;
});

但是我一直遇到忘记在文件顶部添加模块的错误。上面我忘了向我的依赖项添加ImageWrapper。当我这样做时,我的代码静默失败,没有错误消息,即使ImageWrapper undefined。如果我尝试记录console.log(ImageWrapper)我确实会收到错误。

为什么构造函数调用 new ImageWrapper(img) 失败并显示错误?是否有类似于"use strict;"的东西可以用来在开发过程中增加错误信息?

您可以使用

像 http://jshint.com/这样的工具来检查代码 - 你会得到类似的东西:

One undefined variable
27  ImageWrapper

根据您的设置,有不同的方法可以自动执行此操作,一些编辑器已经内置了此功能,或者插件可以扩展此功能。如果你想手动运行jshint,npm上还有一个命令行版本:https://npmjs.org/package/jshint

您的代码应该抛出错误,但前提是您实例化了new Sprite

当我尝试像这样简化您的代码时

define('Sprite', ['underscore'], function(_) {
  'use strict';
  function Sprite() {
    this.init.apply(this, arguments);
  }
  _.extend(Sprite.prototype, {
    init: function() {
      this._foo = new DoesntExist();
    }
  });
  return Sprite;
});
require(['Sprite'], function(Sprite) {
  var sprite = new Sprite();
});

它按预期抛出引用错误。