画布对象文字:未捕获类型错误:无法调用未定义的方法“getContext”

Canvas object literal: Uncaught TypeError: Cannot call method 'getContext' of undefined

本文关键字:调用 未定义 getContext 方法 错误 对象 布对象 文字 类型      更新时间:2023-09-26

为什么使用对象文字(如下所示)会产生此错误?

<canvas id="game" width="568" height="320"></canvas>

var GAME = {
    settings: {
        canvas: document.getElementById('game'),
        context: this.canvas.getContext('2d'),
        gameWidth: this.context.width,
        gameHeight: this.context.height
    }
};

在您的代码中,this是全局上下文,即window 。不能在对象文本的属性中引用对象本身。

一个解决方案:

var GAME = {
    settings: {
        canvas: document.getElementById('game');
    }
};
GAME.settings.context = GAME.settings.canvas.getContext('2d');
GAME.settings.gameWidth = GAME.settings.context.width;
GAME.settings.gameHeight = GAME.settings.context.height;

您可以使用IIFE作为更干净的代码:

var GAME = (function(){
   var s = {};
   s.canvas = document.getElementById('game');
   s.context = s.canvas.getContext('2d');
   s.gameWidth = s.context.width;
   s.gameHeight = s.context.height;
   return { settings : s}
})();