在Javascript中引用对象属性

Con*_*uhl 4 javascript oop object

如果我有代码:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            //How do I reference foo here?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Nea*_*eal 11

你需要一个self参考:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            self.foo; //foo!
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Hal*_*yon 6

function SomeObject() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            self.foo;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)