Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object reference

Tags:

javascript

I'm having an issue with Javascript object literals.

I would like to reference the object within one of the functions:

var Obj = {
    name : "Johnny",
    dumb : function() {
        alert(this.name);
    }
}

Sadly, the "dumb" function is an object as well. So, since dumb() has no 'name' property, it will return as undefined.

How do I get around this?

like image 748
JohnnyStarr Avatar asked Dec 07 '22 17:12

JohnnyStarr


1 Answers

dumb is a method on your Obj object. When called, this will be set to Obj, and will alert "Johnny"

Try it out

var Obj = {
    name : "Johnny",
    dumb : function() {
        alert(this.name);
    }
}

Obj.dumb();
like image 59
Adam Rackis Avatar answered Dec 25 '22 13:12

Adam Rackis