javascript - Defer execution for ES6 Template Literals -
i playing new es6 template literals feature , first thing came head string.format javascript went implementing prototype:
string.prototype.format = function() { var self = this; arguments.foreach(function(val,idx) { self["p"+idx] = val; }); return this.tostring(); }; console.log(`hello, ${p0}. ${p1}`.format("world", "test")); however, template literal evaluated before it's passed prototype method. there way can write above code defer result until after have dynamically created elements?
i can see 3 ways around this:
use template strings designed used, without
formatfunction:console.log(`hello, ${"world"}. ${"test"}`); // might make more sense variables: var p0 = "world", p1 = "test"; console.log(`hello, ${p0}. ${p1}`); // or function parameters actual deferral of evaluation: const welcome = (p0, p1) => `hello, ${p0}. ${p1}`; console.log(welcome("world", "test"));don't use template string, plain string literal:
string.prototype.format = function() { var args = arguments; return this.replace(/\$\{p(\d)\}/g, function(match, id) { return args[id]; }); }; console.log("hello, ${p0}. ${p1}".format("world", "test"));use tagged template literal. notice substitutions still evaluated without interception handler, cannot use identifiers
p0without having variable named so.this behavior may change if different substitution body syntax proposal accepted (update: not).function formatter(literals, ...substitutions) { return { format: function() { var out = []; for(var i=0, k=0; < literals.length; i++) { out[k++] = literals[i]; out[k++] = arguments[substitutions[i]]; } out[k] = literals[i]; return out.join(""); } }; } console.log(formatter`hello, ${0}. ${1}`.format("world", "test")); // notice number literals: ^ ^
Comments
Post a Comment