Gerard Gerard - 1 month ago 24
Java Question

porting java code to javascript

I have a Java class constructor, part of which allows me to set the variable 'key' on instantiation:

public class Note
{
private int key;

public Note()
{
setKey(1 + (int)(Math.random() * 13D));
}

public void setKey(int i)
{
key = (i > 0) & (i <= 13) ? i : 0;
}
}


I would like to rewrite the code in javascript so that I can use it on a webpage without the java runtime environment. I tried:

var Note = function() {
pitch : setKey( Math.floor(Math.random() * 13) + 1);
}

function setKey(i) {
var key = (i > 0) & (i <= 13) ? i : 0;
console.log("Here key is: " + key); // prints a number
return key;
}

var note1 = new Note();
console.log( note1.pitch); // THIS PRINTS UNDEFINED


What am I failing to understand about initialising the variable 'pitch'?

Thanks very much for any help.
Gerard

Answer

That is a label, not a property.

var Note = function() {
    this.pitch = setKey( Math.floor(Math.random() * 13) + 1); 
};

function setKey(i) {
    var key = (i > 0) & (i <= 13) ? i : 0;
    console.log("Here key is: " + key); // prints a number
    return key;
}

var note1 = new Note(); 
console.log( note1.pitch); // THIS PRINTS UNDEFINED