0

为什么使用如下的对象文字会产生此错误?

<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
    }
};
4

1 回答 1

1

在您的代码中,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}
})();
于 2013-09-08T17:42:29.837 回答