Why does this code work...
var message = {
texts: {
text1: 'Hello',
text2: 'World'
},
greet: function() {
console.log(this.texts.text1 + ' ' + this.texts.text2 + '!');
}
}
message.greet();
...but this doesn't?
var message = {
texts: {
text1: 'Hello',
text2: 'World'
},
both: this.texts.text1 + ' ' + this.texts.text2 + '!',
greet: function() {
console.log(this.both);
}
}
message.greet();
It gives me "both is not defined" error. What am I missing here? Something's wrong withthis.both
? I'm total newbie when it comes to object literal
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
ES6 defines 'ComputedPropertyName' as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets. Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console.
Literals represent values in JavaScript. These are fixed values—not variables—that you literally provide in your script.
To create a variable in JavaScript, use the let keyword. To be concise, we can combine the variable declaration and assignment into a single line: let message = 'Hello! '; // define the variable and assign the value alert(message); // Hello!
Because in second case this
is still not exist when you define both
. if you will turn both
to method, like in this example : http://jsfiddle.net/YyWMQ/ , it will work.
both: function(){ return this.texts.text1 + ' ' + this.texts.text2 + '!'}
Imho , good question , +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();
To understand it you can try as given below
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With