Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
access info of the instance from instance function

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);
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda