Quick question, and one I am yet to work out on my own. I'll start with an example.

object = {
    somevariable: true,
    someothervariable:31,
    somefunction: function(input){
        if (somevariable === true){
            return someothervariable+input;
        }
    }
}

object.somefunction(3);

Obviously this won't work. Do I have to say object.somevariable and object.someothervariable or is there a means of referring to variables that are part of the local object, without referring to the object explicitly?

Thanks

Gausie

share|improve this question
feedback

2 Answers

up vote 5 down vote accepted

Use the special keyword this, which refers to the object a function was invoked on:

var thing = {
    somevariable: true,
    someothervariable:31,
    somefunction: function(input){
        if (this.somevariable === true){
            return this.someothervariable+input;
        }
    }
}
thing.somefunction(3);

var otherThing = {
    somevariable: true,
    someothervariable:'foo',
    amethod: thing.somefunction
};
otherThing.amethod('bar');

Be careful about using variable names like "object". JS is case-sensitive, so it won't collide with the intrinsic Object, but you might get into trouble in other languages.

share|improve this answer
This seems obvious, why did I not try it? – Gausie Jan 5 '10 at 15:31
of course, this will work only inside functions... if you have smth like var o = {a:1,b:this.a}; this will definetly won't work – gion_13 Jan 18 '11 at 22:06
feedback

When adding "this" it works for me.

var o = {
    somevariable: true,
    someothervariable:31,
    somefunction: function(input){
        if (this.somevariable === true){
            return this.someothervariable+input;
        }
    }
}

alert(o.somefunction(3));
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.