2016-11-09 58 views
0

我有一个Java类的构造函数,其中一部分让我设置实例变量的“钥匙”:移植Java代码的JavaScript

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 

什么我不理解有关初始化变量“基音”?

非常感谢您的帮助。 杰拉德

+1

监守是在函数内部的标签,而不是一个属性。 – epascarello

+0

这是一个标签,而不是一个属性......你在一个函数中,而不是一个对象......'this.pitch = setKey(...)' – Li357

+0

非常感谢。 – Gerard

回答

0

这是一个label,而不是一个属性。

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

0

你会怎么做POO不使用ES6特点:

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