我有一個函數可以創建一個新的圖像併爲它提供一個事件監聽器,它需要訪問一個全局變量。全局變量(_currentSection)被定義,直到它到達事件偵聽器的聲明,然後變爲未定義。下面是函數:全局變量在事件監聽器中變得未定義 - javascript
function relMouseCoords(event) {
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do {
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
} while (currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
//alert('x: ' + canvasX + ' y: ' + canvasY);
for (var i = 0; i < _currentSection.allHotSpots.length; i++) {
if (canvasX > _currentSection.allHotSpots[i].topLeft[0] &&
canvasX < _currentSection.allHotSpots[i].bottomRight[0] &&
canvasY > _currentSection.allHotSpots[i].topLeft[1] &&
canvasY < _currentSection.allHotSpots[i].bottomRight[1]) {
//alert('x: ' + canvasX + ' y: ' + canvasY);
if (_currentSection.allHotSpots[i].isPicZoom === "false") {
appendHotSpot(_currentSection.allHotSpots[i], _currentSection.thePicture, _context, true);
} else {
picZoomCode = _currentSection.allHotSpots[i].myPicZoom;
var img = new Image();
img.onload = function() {
_context.drawImage(img, 0, 0, _canvas.width, _canvas.height);
}
img.src = "data:image/jpeg;base64," + _currentSection.allHotSpots[i].picture;
img.addEventListener('load', function() {
if (_currentSection.allHotSpots[i].allHotSpots) {
for (var j = 0; j < _currentSection.allHotSpots[i].allHotSpots.length; j++) {
appendHotSpot(_currentSection.allHotSpots[i].allHotSpots[j], _currentSection.allHotSpots[i].thePicture, _context, false)
}
}
}, false);
}
}
}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
左右的時間內img.addEventListener我需要訪問_currentSection,但它只是剛剛進去img.addEventListener不確定的。我如何保持它的定義?
你確定變量實際上是全球性的?嘗試做一個'console.log(window._currentSection);' – 2015-01-26 21:59:27