2013-10-29 211 views
0

我正在写一个音乐相关的程序,并希望在我的对象中有对象作为属性。我知道可以一个一个做,但我想要一条捷径。这是我想要做的,我知道不行。什么是正确的方法?可能吗?如何在JavaScript中使用对象属性创建对象类?

function OctaveNote(note, value) { 
    this.firstOctave = note + 1.value = value; 
    this.secondOctave = note + 2.value = value + 12; 
    this.thirdOctave = note + 3.value = value + 24; 
} 

或者

function OctaveNote(note, value) {  
    this.firstOctave = note + 1; 
    this.firstOctave.value = value; 
    this.secondOctave = note + 2; 
    this.secondOctave.value = value + 12; 
    this.thirdOctave = note + 3; 
    this.thirdOctave.value = value + 24; 
} 

这样C = new OctaveNote ("C", 0);让我知道C3.value = 24和我没有写单个对象为所有11个音符,99行,每倍频程!

+0

我不确定第一个可以工作。什么是1.value? –

+1

'C3.value'是什么意思?你的意思是'C.thirdOctave.value'? – xqwzts

回答

0

是的,但它需要的对象不是字符串。

此创建一个字符串:this.firstOctave = note + 1;

但你不能在propetry value添加到字符串。

所以你需要做的就是创建这样一个对象:

// Constructor 
function OctaveNote(note, value) { 
    // If we have a note and a value, we add a note. 
    if (typeof note !== 'undefined' && typeof value !== 'undefined') this.addNote(note, value); 
} 

OctaveNote.prototype.addNote = function(note, value) { 
    this[note+1] = value; 
    this[note+2] = value + 12; 
    this[note+3] = value + 24; 
} 

var octave = new OctaveNote("B", 14); 
octave.addNote('C', 2); 
octave.addNote('A', 6); 
console.log(octave.C1); // 2 
console.log(octave.A2); // 18 
console.log(octave.C3); // 26 

jsFiddle

0

你的第二个例子应该是一个涵盖你所需要的。你错误的是使用/如何调用它。

当您使用

C = new OctaveNote("C", 0) 

C对象,你现在有OctaveNote一个实例,你可以在构造函数中设置的所有属性访问。

所以,你可以通过调用

C.thirdOctave.value应返回24得到thirdOctave。

这里你的问题是,thirdOctave本身不是一个对象,因此它不能持有属性,如值。您可以将thirdOctave转换为包含字符串和值对的对象,也可以将您的值存储在自己的单独属性中:thirdOctaveValue

所以,你可以改变功能成类似:

function OctaveNote(note, value) { 
    this.firstOctaveName = note + 1; 
    this.firstOctaveValue = value; 
    this.secondOctaveName = note + 2; 
    this.secondOctaveValue = value + 12; 
    this.thirdOctaveName = note + 3; 
    this.thirdOctaveValue = value + 24; 
} 

然后就可以开始,每注对象:

D = new OctaveNote("D", 20); 
X = new OctaveNote("X", 32); 

,并获得价值了出来:

console.log(D.firstOctaveValue); 
console.log(X.secondOctaveValue); 

etc