When passing a callback, is doing so by value:
utility.subscribe(this.callback);
not the same as passing it as its expanded form?
utility.subscribe(arg => this.callback(arg));
I had the understanding that they are equivalent, but encountered a problem when context was needed to be passed together with the callback.
var utility = {
name: 'utility',
subscribe(callback) {
var msgForCallback = 'Hey callback!';
callback(msgForCallback);
}
}
var user = {
name: 'user',
useSubscriber() {
utility.subscribe(
this.callback
);
},
useSubscriberWithArrow() {
utility.subscribe(
arg => this.callback(arg)
);
},
callback (arg) {
console.log(`Context: ${this.name}`);
console.log(`The utility says: ${arg}`);
}
}
console.log('\nCall user.useSubscriber();');
user.useSubscriber();
console.log('\nCall user.useSubscriberWithArrow();');
user.useSubscriberWithArrow();
I realize that the callback function is a regular function, and that's why the context may be lost. So I tried changing it to an arrow function, but then even the call with an expanded callback loses the context.
callback: (arg) => { .. }
instead of
callback (arg) { .. }
var utility = {
name: 'utility',
subscribe(callback) {
var msgForCallback = 'Hey callback!';
callback(msgForCallback);
}
}
var user = {
name: 'user',
useSubscriber() {
utility.subscribe(
this.callback
);
},
useSubscriberWithArrow() {
utility.subscribe(
arg => this.callback(arg)
);
},
callback: (arg) => {
console.log(`Context: ${this.name}`);
console.log(`The utility says: ${arg}`);
}
}
console.log('\nCall user.useSubscriber();');
user.useSubscriber();
console.log('\nCall user.useSubscriberWithArrow();');
user.useSubscriberWithArrow();