In javascript, how do you call a function?

261
1
04-29-2023 04:56 AM
hectorsalamanca
New Contributor III

I've written a constructor function that registers an event handler:

 

 

function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}

// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1200);
}
};

// called as
var obj = new MyConstructor('foo', transport);

 

 


However, I am unable to access the created object's data property within the callback. It appears that this does not refer to the object that was created, but to another.

I also attempted to use an object method rather than an anonymous function:

 

 

function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}

MyConstructor.prototype.alert = function() {
alert(this.name);
};

 

 

However, it has the same issues.

How do I get to the right object?

0 Kudos
1 Reply
KenBuja
MVP Esteemed Contributor

When JS used Dojo (before 4.18 and 3.x), using lang.hitch was the proper way to make sure that "this" retains the proper context.

In ES6, arrow function were introduced where the "this" scope is better preserved.

0 Kudos