1

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems obvious, why did I not try it?
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
1

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

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.