将代码转换为JS对象文字模式

Convert code to JS Object Literal Pattern

本文关键字:对象 文字 模式 JS 代码 转换      更新时间:2023-09-26

我想开始编写更好的代码,并且我已经开始理解将与特定功能部分相关的所有内容放在对象中是一个好主意。

编辑:我试着在@SoftwareEngineer171的回答中接受这个概念。现在我有了这个:
var app = {
    audioCtx : new(window.AudioContext || window.webkitAudioContext)(),
    init : function () {
        oscillator = app.audioCtx.createOscillator();
        oscillator.type = 'square';
        oscillator.frequency.value = 3000; // value in hertz
        oscillator.start();
    }
} // app object close
app.init();

但是它不起作用。有人能解释一下原因吗?

我想把这段代码用作应用程序的一部分,但是放在对象文字中:

var context = new AudioContext(), 
    gainNode = context.createGain(), 
    oscillator = context.createOscillator();
gainNode.connect(context.destination);
oscillator.frequency.value = 440;
oscillator.connect(gainNode);
oscillator.start();

然而,当我尝试时,我遇到了这里提到的那种问题。

我希望代码像这样开始:

var app = {
    context : new AudioContext(),
    ...
}

如有任何帮助,不胜感激。

您要做的不是特定的功能,但是您可以通过几种方式来实现。例如,如果您想编写以下对象

var obj = {
    a: 5,
    b: 7,
    c: a + b
};

将抛出一个ReferenceError。为了避免这种情况,可以将语法重写为

var obj = {
    a: 5,
    b: 7,
    init(){
        this.c = this.a + this.b;
        return this;
    }
}.init();

也可以使用class

var obj = new class{
    constructor(){
        this.a = 5;
        this.b = 7;
        this.c = this.a + this.b;
    }
}();

或者甚至使用构造函数

var obj = new function(){
    this.a = 5;
    this.b = 7;
    this.c = this.a + this.b;
}();

编辑

在您的例子中,音频上下文脚本看起来像这样(参见JSFiddle):

var app = {
  context: new (window.AudioContext || window.webkitAudioContext)(),
  gainNode: null,
  oscillator: null,
  init(){
    this.gainNode = this.context.createGain();
    this.oscillator = this.context.createOscillator();
    this.gainNode.connect(this.context.destination);
    this.oscillator.frequency.value = 440;
    this.oscillator.connect(this.gainNode);
    this.oscillator.start();
  }
};
app.init();