为什么使用对象文字(如下所示)会产生此错误?
<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
}
};
答案 0 :(得分: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}
})();