gpt4 book ai didi

javascript - 创建一个音频元素并在对象文字中赋予它属性

转载 作者:行者123 更新时间:2023-12-03 05:52:12 31 4
gpt4 key购买 nike

我正在努力改掉编写意大利面条式代码的坏习惯。我在 modular javascript 上找到了一个很棒的教程我正在尝试将其应用到我的一个项目中。

我有这个:

var sfx = {}

sfx.mySound1 = document.createElement('audio');
sfx.mySound1.src = 'https://some-url.ogg';
sfx.mySound1.moreProps = "...";

sfx.mySound2 = document.createElement('audio');
sfx.mySound2.src = 'https://some-url.ogg';
sfx.mySound2.moreProps = "...";

在另一个对象中我可以播放这样的声音效果:

sfx.mySound1.play();

我想实现同样的目标,但我想使用对象文字模式:

const sfx = {
mySound1: {
// create audio element
// give it props
},
mySound2: {
// create audio element
// give it props
}
}

我似乎无法弄清楚如何创建音频元素并在同一对象中为其赋予属性。也许这违背逻辑并且不应该起作用。如果是这样,我应该如何编写它以将其全部保留在 sfx 对象 中?

最佳答案

试试这个:

var sfx = {
mySound1: Object.assign(document.createElement('audio'), {
src: 'https://some-url.ogg',
moreProps: '...'
}),

mySound2: Object.assign(document.createElement('audio'), {
src: 'https://some-url.ogg',
moreProps: '...'
})
}

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

看起来够清楚了,但是引用Object.assign()有关浏览器兼容性和 polyfill 的文档。

关于javascript - 创建一个音频元素并在对象文字中赋予它属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100153/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com