2013-06-21 12 views
8

Dlaczego ten kod praca ...nie można zdefiniować zmienną w JavaScript Object dosłowne

var message = { 
    texts: { 
     text1: 'Hello', 
     text2: 'World' 
    }, 
    greet: function() { 
     console.log(this.texts.text1 + ' ' + this.texts.text2 + '!'); 
    } 
} 
message.greet(); 

... ale to nie robi?

var message = { 
    texts: { 
     text1: 'Hello', 
     text2: 'World' 
    }, 
    both: this.texts.text1 + ' ' + this.texts.text2 + '!', 
    greet: function() { 
     console.log(this.both); 
    } 
} 
message.greet(); 

Daje mi "błąd nie zdefiniowany". Czego tu mi brakuje? Coś jest nie tak z this.both? Jestem totalną nowicjuszką, jeśli chodzi o literalną nazwę obiektu

+0

'TypeError: nie można odczytać właściwość 'text1 odwiedzający undefined' –

+0

Czy to tylko ja czy powinna oba przykłady nie działać – aaronman

Odpowiedz

6

Ponieważ w drugim przypadku this nadal nie istnieje po zdefiniowaniu both. jeśli zamienisz both na metodę, jak w tym przykładzie: http://jsfiddle.net/YyWMQ/, to zadziała.

both: function(){ return this.texts.text1 + ' ' + this.texts.text2 + '!'} 

IMHO, dobre pytanie, +1

1
var message = { 
    texts: { 
     text1: 'Hello', 
     text2: 'World' 
    }, 
    // here this refers to the scope where message is defined 
    both: this.texts.text1 + ' ' + this.texts.text2 + '!', 
    greet: function() { 
     console.log(this.both); 
    } 
} 
message.greet(); 

Aby zrozumieć to można spróbować, jak podano poniżej

this.texts = { 
      text1: 'Alternate Hello', 
      text2: 'World' 
     }; 

var message = { 
     texts: { 
      text1: 'Hello', 
      text2: 'World' 
     }, 
     // here this refers to the scope where message is defined 
     both: this.texts.text1 + ' ' + this.texts.text2 + '!', 
     greet: function() { 
      console.log(this.both); 
     } 
    } 
message.greet(); 
1

Twój nieporozumienie jest w następujący wiersz:

both: this.texts.text1 + ' ' + this.texts.text2 + '!', 

Można użyć jako zabawy ction i zwraca wartości jak:

both: function(){ return this.texts.text1 + ' ' + this.texts.text2 + '!'; } , 

i wreszcie

greet: function() { 
     console.log(this.both()); 
    } 
1

Dzwoniąc pozdrawiam, `to będzie obj dominująca wiadomość. Nie dzieje się tak podczas konstruowania obiektu wiadomości. można napisać coś podobnego jak:

var Message = function() { 
    this.texts = { 
     text1: 'Hello', 
     text2: 'Word' 
    } 
    this.both = this.texts.text1 + ' ' + this.texts.text2 + '!'; 
} 

Message.prototype.greet = function() { 
    console.log(this.both); 
} 

message = new Message(); 
message.greet();