2017-07-27 350 views
1

HTML類型錯誤:this.canvas未定義(在聲明的對象)

<canvas id="ctx"></canvas> 

的JavaScript

var objMap = { 
htmlID: 'ctx', 
canvas: document.getElementById(this.htmlID), 
ctx: this.canvas.getContext('2d')}; 

在控制檯中的誤差出現。 「TypeError:this.canvas is undefined」 我真的想在對象中的變量中有這個。

回答

1

不,你不能用直接對象來做到這一點。然而,使用匿名函數,您可以嘗試構建您的對象。

var objMap = new function() { 
this.htmlID= 'ctx'; 
this.canvas= document.getElementById(this.htmlID); 
this.ctx= this.canvas.getContext('2d'); 
}; 
+0

如果我做這樣的事情會是一樣的嗎?函數Map(){this.htmlID ='ctx'; this.canvas = document.getElementById(this.htmlID); this.ctx = this.canvas.getContext('2d');} var objMap = new Map(); – Steve143

+1

是的,它是...... –

+0

非常感謝! – Steve143