Javascript对象:从方法中访问对象变量

Gau*_*sie 1 javascript oop json

快问题,还有一个我自己要解决的问题.我将从一个例子开始.

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

object.somefunction(3);
Run Code Online (Sandbox Code Playgroud)

显然这不起作用.我是否必须说object.somevariable和/ object.someothervariable或是否有一种方法可以引用属于本地对象的变量,而无需明确引用该对象?

谢谢

Gausie

out*_*tis 5

使用special关键字this,该关键字引用调用函数的对象:

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');
Run Code Online (Sandbox Code Playgroud)

注意使用像"对象"这样的变量名称.JS区分大小写,因此它不会与内在冲突Object,但您可能会遇到其他语言的麻烦.