Skip to content

Instantly share code, notes, and snippets.

@Teino1978-Corp
Created November 10, 2015 04:32
Show Gist options
  • Save Teino1978-Corp/b62f35e3392bd0a0bb48 to your computer and use it in GitHub Desktop.
Save Teino1978-Corp/b62f35e3392bd0a0bb48 to your computer and use it in GitHub Desktop.
Applying context of functions to JavaScript variable
String.prototype.interpolate = function(props) {
return this.replace(/\{(\w+)\}/g, function(match, expr) {
return (props || window)[expr];
});
};
// Test:
// Using the parameter (advised approach)
document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 });
// Using the global scope
var eruption2 = 116;
document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment