I'm working on a JS script to render a guitar fretboard. I need to declare two static vars in my class. One object to map note names like "C#" onto their integer MIDI note the other an array of objects providing details for each midi mote. It looks like I have to declare these after the class/function itself but I want to be sure I can refer to them in the constructor function.
Complicating matters is that I want to namespace my code inside an anonymous function to prevent name collisions--I understand these are best practices.
I've been puttering around with some code and have something like this, but I don't think the stuff at the end is going to work.
(function(){
// object to encapsulate this module
var MyClass = function() {
this.foo = "foo";
this.bar = "bar";
};
MyClass.nameToMidiNumber = {"C0":0,"C#0":1,"Db0":1,"D0":2,"D#0":3,"Eb0":3}; // and so on
MyClass.midiData = [{"octave":0,"utf8_name":"C","ascii_name":"C","frequency":8.1757989156},{"octave":0,"utf8_name":"C♯\/D♭","ascii_name":"C#\/Db","frequency":8.661957218}]; // etc
if(typeof window!="undefined"){
window.MYNAMESPACE || (window.MYNAMESPACE = {});
if(window.MYNAMESPACE.MyClass){
for(var prop in MyClass){
window.MYNAMESPACE.MyClass[prop]=MyClass[prop]
}
}else{
window.MYNAMESPACE.MyClass=MyClass
}
} else {
throw "'window' not defined. Unable to attach MyClass.";
}
})();
Am I doing this right? Ideally, after including this script with an HTML tag:
<script type="text/javascript" src="myscript.js"></script>
then I could just instantiate the object like so:
var gtr = new MYNAMESPACE.MyClass(prm1, prm2, prm3);
I'm also aware that a transition is currently underway to ES6 which has the class and static keywords. Should I be using that instead?