Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!