##Here are several ways to access the parent context inside a child context -
Here are several ways to access the parent context inside a child context -
- You can use the
bind()
function. - Store a reference to context/this inside another variable (see the below example).
- Use ES6 Arrow functions.
- Alter the code, function design, and architecture - for this you should have command over design patterns in JavaScript.
#1. Use the bind()
function
1. Use the bind()
function
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', ( function () {
alert(this.data);
}).bind(this) );
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);
If you are using Underscore.js - http://underscorejs.org/#bind
transport.on('data', _.bind(function () {
alert(this.data);
}, this));
#2 Store a reference to context/this inside another variable
2. Store a reference to context/this inside another variable
function MyConstructor(data, transport) {
var self = this;
this.data = data;
transport.on('data', function() {
alert(self.data);
});
}
#3 Arrow function
3. Arrow function
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => {
alert(this.data);
});
}