函数中定义的变量导致引用错误:未定义
Variable defined within function causing reference error: not defined
我正在通过这本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
现在从我的角度来看,这是因为source
已使用 var
关键字定义,使其范围限定为 play()
函数,因此pause()
无法访问。删除 var
关键字确实可以解决问题。有人可以向我保证我的推理是正确的吗?这只是一个错字,还是有一些我不理解的基本原则?(我已经检查了这本书的勘误表,那里没有提到它。
使source
成为全局变量,就像startOffset
和startTime
一样。
在函数中声明一个变量使其成为局部变量,即它只存在于该函数中,因此只能在该函数中引用。将其声明为全局变量将使其可用于任何 Javascript 函数,但您通常希望尽可能少地污染全局命名空间:
function AudioPlayer(buffer) {
this.startOffset = 0;
this.startTime = 0;
this.source = null;
this.buffer = buffer;
}
AudioPlayer.prototype.pause = function() {
if (!this.source) {
return;
}
this.source.stop();
// Measure how much time passed since the last pause.
this.startOffset += context.currentTime - this.startTime;
}
AudioPlayer.prototype.play = function() {
this.startTime = context.currentTime;
this.source = context.createBufferSource();
// Connect graph
this.source.buffer = this.buffer;
this.source.loop = true;
this.source.connect(context.destination);
// Start playback, but make sure we stay in bound of the buffer.
this.source.start(0, this.startOffset % this.buffer.duration);
}
这允许您像这样调用这些函数:
var player = new AudioPlayer(buffer);
player.play();
player.pause();
试试这个:
function a(advName,area) {
onclick="sub(''' +advName+ ''',''' +area+ ''');"
}
相关文章:
- gmaps4rails 2.4.6未捕获引用错误:未定义Gmaps
- Wordpress中的Javascript出现匿名函数/引用错误
- 使用dc.js、d3.js和crossfilter引用错误
- 未捕获引用错误:未定义validateform
- 为什么我会出现此错误"未捕获引用错误:未定义标题;
- $未定义-未捕获引用错误
- Sitecore”;未捕获引用错误:未定义MultilistWithSearch;
- Wordpress:未捕获引用错误:未定义速度
- Node.js引用错误:未定义类名
- 我该如何解决“;未捕获引用错误:谷歌没有定义"?(谷歌地图API)
- 调用setTimeout内部的函数时发生引用错误
- 未捕获的引用错误:未定义<映射键>
- Javascript错误:未捕获引用错误:未定义编辑
- Google可视化addListener调用函数引用错误
- Cordova:未捕获引用错误:chbrody没有使用SQLitePlugin.js定义PhoneGap
- 未捕获引用错误:未定义PrintThisPage
- 引用错误:在尝试使用ajax发送数据时未定义
- 包含的文件中引发引用错误..除非调用文件包含慢速代码
- 在表单提交按钮的点击事件中调用函数时发生引用错误
- 未捕获引用错误:幻灯片未定义