I have this simple code:
function fetch(callback) {
const data = [1, 2, 3];//from query to server
callback(data);
callback.prototype.log.call(); // PROBLEM HERE. I want to log the fetchCallback instance data array from here
}
function fetchCallback() {
this.data = []
}
fetchCallback.prototype.store = function(data) {
data.forEach(el => this.data.push(el));
console.log(this.data); //here the log works because of the instance binding
}
fetchCallback.prototype.log = function() {
console.log(this.data);
}
const mycallback = new fetchCallback();
fetch(mycallback.store.bind(mycallback));
In function fetch(callback) {...} I want to be able to access the callback holder instance, which is mycallback to log the this.data of that instance. I tried callback.prototype.log.call();, callback.log();, and some others, but I am missing something regarding the scope/context topic.
Edit:
This seems to work if the whole instance is passed through:
function fetch(callback) {
const data = [1, 2, 3];//from query to server
callback.store(data);
callback.log();
}
const mycallback = new fetchCallback();
//fetch(mycallback.store.bind(mycallback));
fetch(mycallback);
Edit2: Data hold and store functions separated
function fetch(callback, dataHolder) {
const data = [1, 2, 3];//from query to server
callback(data, dataHolder);
log(dataHolder.data);
}
function dataHolder() {
this.data = []
}
function store(data, holder) {
data.forEach(el => holder.data.push(el));
//console.log(this.data);
}
function log(data) {
console.log(data);
}
const myDataHolder = new dataHolder();
//fetch(mycallback.store.bind(mycallback));
fetch(store, myDataHolder);