javascript - 函数内定义的变量导致引用错误 : not defined

标签 javascript function scope web-audio-api

我正在学习这本 O'Reilly 书中的一些网络音频教程:http://chimera.labs.oreilly.com/books/1234000001552/ch02.html#s02_2

以下代码应该创建一个系统来暂停音频文件并恢复播放。

// Assume context is a web audio context, buffer is a pre-loaded audio buffer.
var startOffset = 0;
var startTime = 0;

function pause() {
  source.stop();
  // Measure how much time passed since the last pause.
  startOffset += context.currentTime - startTime;
}

function play() {
  startTime = context.currentTime;
  var source = context.createBufferSource();
  // Connect graph
  source.buffer = this.buffer;
  source.loop = true;
  source.connect(context.destination);
  // Start playback, but make sure we stay in bound of the buffer.
  source.start(0, startOffset % buffer.duration);
}

但是,运行 pause() 函数会导致以下错误:

Uncaught ReferenceError: source is not defined 

现在从我的 Angular 来看,这是因为 source 已使用 var 关键字定义,使其作用域为 play() 函数,因此无法访问 pause()。删除 var 关键字确实可以解决问题。有人可以让我放心我的推理是正确的吗?这只是一个错字,还是有一些我不理解的基本原理? (我检查了这本书的勘误表,那里没有提及它。)

最佳答案

source 设为全局变量,就像 startOffsetstartTime 一样。

关于javascript - 函数内定义的变量导致引用错误 : not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364588/

相关文章:

javascript - 增加节点大小 vis.js

javascript - 使用 jQuery 查找文章正文

c - 头文件中声明的函数错误 : conflicting types for function,

javascript - 将 JavaScript 函数作为参数传递

powershell - 在 Jenkins 构建的 Windows Powershell 中设置的变量,在其他构建步骤中不可用

javascript - jquery重置setInterval时间

javascript - Royalslider JavaScript slider .next()

function - 有或没有类型注释会发生特化吗?

c - 如何使指针变量在函数中可见

php - 可变变量的意外行为