[英]porting java code to javascript
我有一个Java类构造函数,部分构造函数允许我在实例化时设置变量'key':
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;
}
}
我想用javascript重写代码,以便无需Java运行时环境就可以在网页上使用它。 我试过了:
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
关于初始化变量“ pitch”,我不了解什么?
非常感谢您的帮助。 杰拉德
那是标签 ,而不是属性。
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
不使用ES6功能时如何做POO:
function Note() { // constructor this.pitch = this.setKey(Math.floor(Math.random() * 13) + 1); } Note.prototype.setKey = function(i) { return (i > 0) & (i <= 13) ? i : 0; } var note = new Note(); console.log(note.pitch);
如果要使用ES6功能(例如,使用像babel这样的预编译器):
class Note { constructor() { this.pitch = this.setKey(Math.floor(Math.random() * 13) + 1); } setKey(i) { return (i > 0) & (i <= 13) ? i : 0; } } let note = new Note(); console.log(note.pitch);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.