我试图通过返回time_pressed并在函数外部进行function held()来访问time_pressed之外的console.log(held())变量。它是console.log -ing undefined。为什么它不起作用,我该怎么做才能在函数外部访问所述变量?

这是我的代码。

function held(){
    var time_pressed;
    document.onmousedown = function(e){
        mousedown_time = getTime();
        console.log(mousedown_time);
    }
    document.onmouseup = function(e){
        time_pressed = getTime() - mousedown_time;
        console.log('You held your mouse down for', time_pressed,'miliseconds.');
    }
    return time_pressed
}
console.log(held())

最佳答案

考虑以下功能:

function held(){
    var time_pressed;
    return time_pressed;
}
console.log(held());


您期望函数返回什么?没有定义值,因此值为undefined

您在该函数中唯一要做的就是将事件处理函数分配给文档。这意味着两件事:


这些是单独的函数,它们返回的不是此函数返回的。
这些功能只有在以后的某个时间才会执行。


您已经成功创建了这些事件处理程序。因此尚不清楚为什么要尝试记录一些返回值。您正在执行的函数不会返回任何内容,也不需要返回任何内容。没有什么可记录的。您的事件处理程序在执行时将登录到控制台。

09-11 19:08
查看更多