我正在重新组织一些代码,以使变量对各种函数可见。我有一个名为getMouseXY
的函数,当函数处于全局环境中时(不是从另一个函数调用),它可以正常工作。但是,当我将此函数放在另一个函数中时,它给出了一个错误:Uncaught TypeError: undefined is not a function
我确定它来自d3.mouse(this)
。我问控制台是什么'这个',它是窗口,这似乎是合理的。作为替代方案,我尝试使用.pageX
方法,但这可以使用错误的坐标。如果有必要,我可以解决这个问题,但我不明白为什么我的原始方法在这种情况下会失败。对不起,这不是一个有效的例子,但有人可以解释为什么会抛出错误吗?从主线程调用activateGuides
。这是代码:
var activateGuides = function() { // controls the guides (cursor) in the contour area
var getMouseXY = function() { // get the mouse coordinates & report in terms of [0...1] in the contour area
// var mouse = d3.mouse(this); // error: undefined, but this = window
// mX = mouse[0];
// mY = mouse[1];
mX = d3.event.pageX; // this approach works with slightly wrong coords
mY = d3.event.pageY;
mX = mX - lPad // offset reference point (ul corner of contour is 0,0)
mY = mY - tPad
if (mX < 0) {mX = 0}; // truncate low
if (mY < 0) {mY = 0};
if (mX > conWidth) {mX = conWidth}; // truncate high
if (mY > conHeight) {mY = conHeight};
mX = mX/conWidth // as fraction
mY = mY/conHeight
followMouse(mX, mY); // draws guidelines at the mouse position
document.Show.mouseX.value = mX;
document.Show.mouseY.value = mY;
} // end of getMouseXY
} // end of activateGuides