Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing "this" inside an object

Tags:

javascript

oop

I'm having some trouble in a pretty big body of code I've been writing, and I've boiled it down to this:

var Thing = function(argument){
    this.property = argument;
    this.obj = {
        func: function(){
            return this;
        }
    };
    this.func = function(){
        return this;
    };
};

I need to access this.property inside obj.func(). However, the value of this isn't what I expect it to be:

> var thing = new Thing("value")
> thing.func()
Thing {property: "value", obj: Object, func: function}
> thing.obj.func()
Object {func: function}

When I instantiate an instance called "thing" and call thing.func(), this holds the current instance of Thing, as it should. But when I call thing.obj.func(), it holds the value of thing.obj. What's going on? How do I access that value?

like image 532
Dan Hlavenka Avatar asked Jan 11 '23 23:01

Dan Hlavenka


2 Answers

var thing = new Thing('value')
thing.obj.func() // this inside func will be the object before .func, which is thing.obj

One solution is to bind the function to your object:

var Thing = function(argument){
    this.property = argument;
    this.obj = {
        func: function(){
            return this;
        }.bind(this);    // bind it to the current object
    };
    this.func = function(){
        return this;
    };
};

Alternatively you could use a closure with a private copy of this:

var Thing = function(argument){
    var that = this;
    this.property = argument;
    this.obj = {
        func: function(){
            return that;
        }
    };
    this.func = function(){
        return this;
    };
};
like image 172
Tibos Avatar answered Jan 25 '23 07:01

Tibos


Declare a local variable in the constructor, and assign it the value of this:

var Thing = function(argument){
    var theThing = this;

You can then use "theThing" to refer to the constructed object in those functions.

In your existing code, when you call thing.obj.func(), the value of this in the function will indeed be this.obj. That's because the value of this is determined based on the circumstances of the function call. In that case, the reference to the function ("func") is obtained by traversing its property name on the "obj" object. Therefore, the "obj" object is what this references.

like image 36
Pointy Avatar answered Jan 25 '23 08:01

Pointy