Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Object Properties in Javascript

If I have The code:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            //How do I reference foo here?
        }
    }
}
like image 722
Conner Ruhl Avatar asked Nov 29 '22 16:11

Conner Ruhl


2 Answers

You need a self reference:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            self.foo; //foo!
        }
    }
}
like image 134
Naftali Avatar answered Dec 04 '22 13:12

Naftali


function SomeObject() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            self.foo;
        }
    }
}
like image 36
Halcyon Avatar answered Dec 04 '22 13:12

Halcyon