Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't define variable in JavaScript object literal [duplicate]

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

like image 629
Robert Kirsz Avatar asked Jun 21 '13 12:06

Robert Kirsz


People also ask

Does JavaScript object allow for duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Is there a way to use variable keys in a JavaScript object literal?

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.

What is variable literal in JavaScript?

Literals represent values in JavaScript. These are fixed values—not variables—that you literally provide in your script.

How do you initialize a variable in JavaScript?

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!


2 Answers

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

like image 182
Ivan Chernykh Avatar answered Sep 20 '22 12:09

Ivan Chernykh


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();
like image 20
Diode Avatar answered Sep 18 '22 12:09

Diode