Convert code to JS Object Literal Pattern

时间:2016-08-31 18:30:21

标签: javascript oop audiocontext

I want to start writing better code and I have come to understand that putting everything relevant to a particular piece of functionality inside an object is a good idea.

Edit: I've tried to take on board the concept in @SoftwareEngineer171's answer. Now I have this:

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();

But it doesn't work. Can anyone explain why?

I want to use this code as part of an application, but placed inside an object literal:

var context = new AudioContext(), 
    gainNode = context.createGain(), 
    oscillator = context.createOscillator();

gainNode.connect(context.destination);
oscillator.frequency.value = 440;
oscillator.connect(gainNode);
oscillator.start();

However, when I have tried, I run into problems of the kind mentioned here.

I want the code to begin like this:

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

Any help much appreciated as usual.

1 个答案:

答案 0 :(得分:3)

What you are trying to do is not a particular piece of functionality, but you can do it in several ways. For example, if you want to write the following object

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

it will throw an ReferenceError. To avoid it, rewrite the syntax as following

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

You can also do it using class

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

or even using constructor function

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

Edit

In your case, audio context script will look like this (see also 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();