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