milanHrabos
milanHrabos

Reputation: 1965

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

Upvotes: 0

Views: 85

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

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();

Upvotes: 1

Related Questions