0

Okay this seems really simple but I just can't get it to work. I need to combine variables in an obect. Something like this:

var i = {
    a: 1,
    b: " sheep",
    c: this.a + this.b
}

So that later on I can do something like:

i.a = 3;
console.log(i.c);

and get "3 sheep".

Is this just silly? Or what is the closest thing to it?

3 Answers 3

6

Use a function.

var i = {
    a: 1,
    b: " sheep",
    c: function () {
        return this.a + this.b;
    }
}

i.a = 3;
console.log(i.c());

This looks like it but is there anyway to avoid the function call (). I've seen get and set used in objects. Is this something that is widely used?

Sure, you can use getters, but they won't work in IE <9 (while the above code will), and there's no way to shim it since it relies on a completely new language syntax.

var i = {
    a: 1,
    b: " sheep",
    get c() {
        return this.a + this.b;
    }
}

i.a = 3;
console.log(i.c);
Sign up to request clarification or add additional context in comments.

1 Comment

This looks like it but is there anyway to avoid the function call (). I've seen get and set used in objects. Is this something that is widely used?
2

It is possible in object literal only if you do:

var i = {
    a: 1,
    b: " sheep",
    c: function() { return this.a + this.b; }
};

console.log( i.c() );

Comments

2
var i = {
    a: 1,
    b: " sheep",
    c: function () { return this.a + this.b }
}

i.a = 3;
console.log(i.c());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.