简体   繁体   中英

Javascript Objects: Accessing object variables from methods

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM