TJR
TJR

Reputation: 6577

Use Template Strings (ES6) as a returned variable in a function

I am looking for a way to use a Template String from a variable in function.

This is a working example (not a variable)

let f = function () {
  return `Hello ${this.name}!`
}
f.bind({
  name: 'Stackoverflow-User'
})(); // Hello Stackoverflow-User!

This is the not working example (in a variable)

let s = `Hello ${this.name}!`;
let f = function () {
  return s;
}
f.bind({
  name: 'Stackoverflow-User'
})(); // Hello undefined!

Upvotes: 1

Views: 2025

Answers (1)

c-smile
c-smile

Reputation: 27460

This:

let f = function () {
  return `Hello ${this.name}!`
}

gets compiled into this:

let f = function () {
  return "Hello " + this.name.toString() + "!";
}

and it will work as soon as f is called as a method of proper object. Expression gets evaluated each time you call the function.

And in your second case:

var s = "Hello " + this.name.toString() + "!";

let f = function () {
  return s;
}

that s gets its value only once - at load time and with wrong this.

The only way to make it work that way is to generate function from it:

let s = new Function("return `Hello ${this.name}!`;");

and use it as:

let f = function () {
  return s.call(this);
}

A bit weird but will work.

Upvotes: 2

Related Questions