'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
Solution 1:[1]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CertainPerformance |