0

I was answering a question here Is there a JavaScript equivalent of rubys "#{}" sequences? when i run in a problem with javascript prototype. I wanted to provide an alternative way of the first working function which gives a ruby way of printing, formatting and concatenating strings. Why is the normal function working and the prototype function not ?

<script>
function p(str){
  document.write(str.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"<br>");
}

String.prototype.p = function() {
  return this.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"<br>";
};


var f="foo", b="bar"
p("#{f} #{b}")
document.write("#{f} #{b}".p);

</script>

this gives

foo bar
function () { return this.replace(/#{(\w)}/g, function(match, s){return eval(s)})+"
"; }

the first line is correct, it is the concatenated string, the second line is the function itself that is printed, not the result..

Community
  • 1
  • 1
peter
  • 41,770
  • 5
  • 64
  • 108

1 Answers1

2

"#{f} #{b}".p refers to the function itself (String.p), because "#{f} #{b}" is a string.

You want "#{f} #{b}".p() for it to print foo bar.

Heitor Chang
  • 6,038
  • 2
  • 45
  • 65