我的音频是在对象属性的功能内创建的,但是我需要在单独的对象属性的功能内将其暂停。是否有一种简单的方法可以执行而无需重新构造我的代码?
let audio = {
train: function() {
let train = new Audio(
"audio link"
);
train.play();
}
}
let otherObject = {
pauseAudio: function() {
Audio.pause();
}
train
元素需要暴露在audio
对象之外,以使其他外部变量(例如otherObject
)能够看到它,这是由于常规作用域规则所致。一种可能是audio
具有另一个属性,即其属性指向Audio
实例的子对象:
const audio = {
audioElements: {},
train: function() {
this.audioElements.train = new Audio(
"audio link"
);
this.audioElements.train.play();
}
}
const otherObject = {
pauseAudio: function() {
for (const audioElm of Object.values(audio.audioElements)) {
audioElm.pause();
}
}
}
尚不清楚每次调用train
时是否真的要制作单独的音频元素。如果没有,请首先检查该属性是否存在于音频持有人对象上:
const audio = {
audioElements: {},
train: function() {
if (!this.audioElements.train) {
this.audioElements.train = new Audio(
"audio link"
);
}
this.audioElements.train.play();
}
}
let otherObject = {
pauseAudio: function() {
for (const audioElm of Object.values(audio.audioElements)) {
audioElm.pause();
}
}
}
这将很容易扩展为任何数量的音频元素/方法。