alps
alps

Reputation: 183

Accessing this from inside object's function without callbacks?

I'm trying to call an object (this) (in the example it's o) from within its children.

As shown in the example: I have 10 instances of o inside wrap.instances and I want to call one of these instances from DOM call, via wrap. When I call a var t (this) is set to a() -- how can I set the scope to o instead of its function?

Thanks!

//DOM call
$('#app').on('click', '[call]', function(e) {
    wrap.call($(this).attr('call'));
});

//Wrap
const wrap = {
    instances: {},
    call: function(k) {
        this.instances[k].fn.a();
    }
}

//Instance o
let o = {
    fn: {
        a: function() {
            var t = this; //This is a, not o
            t.fn.b(); //Error, since scope is function a
        },
        b: function() { }
    }
};

Upvotes: 0

Views: 34

Answers (3)

CertainPerformance
CertainPerformance

Reputation: 370689

Because your calling context is fn, another option would be to change the a function to call this.b (so as to refer to fn.b) rather than this.fn.b (which would require a non-standard calling context of o):

let o = {
    fn: {
        a: function() {
            this.b();
        },
        b: function() { }
    }
};

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138257

You could just .bind the function to o:

let o = {};
Object.assign(o, {
  fn: {
    a: function() {
        var t = this; // this is o
        t.fn.b(); // no error
    }.bind(o),
    b: function() { }.bind(o)
  }
});

Upvotes: 0

corolla
corolla

Reputation: 5656

try:

this.instances[k].fn.a.apply(this.instances[k]);

Upvotes: 2

Related Questions