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

174
Visualizações
How to use this keyword inside eval in javascript?

Having this:

const person = {
  name: "James Smith",
  hello: function (x) {
    console.log(this.name + " says hello " + x);
  }
}

function newContext() {
  this.name = "Someone else";
  const code = "(function(){person.hello}).bind(this);"
  eval(code);
}

newContext();

There is not output. But don't know why

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You aren't calling the function here:

(function(){person.hello}).bind(this);

is

(function(){
  person.hello
}).bind(this);

where person.hello is just an unused expression. You need person.hello (not wrapped in a function) to be on the left-hand side, and you also need to actually call it, with () afterwards - or by using .call. You also might want to pass an argument (the x).

const person = {
  name: "James Smith",
  hello: function (x) {
    console.log(this.name + " says hello " + x);
  }
}

function newContext() {
  this.name = "Someone else";
  const code = "person.hello.call(this, 'xx');"
  eval(code);
}

newContext();

const person = {
  name: "James Smith",
  hello: function (x) {
    console.log(this.name + " says hello " + x);
  }
}

function newContext() {
  this.name = "Someone else";
  const code = "person.hello.bind(this)('xx');"
  eval(code);
}

newContext();

about 4 years ago · Juan Pablo Isaza Relatório
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