views:

141

answers:

2

Hi all,

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

+5  A: 

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.

outis
This seems obvious, why did I not try it?
Gausie
+1  A: 

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));
jessegavin