-1

In Ruby we can add a new method to a previously defined class by dynamically modifying it at runtime:

class String
  def to_magic
    "magic"
  end
end

Is it possible to do the same in JavaScript? If yes, how?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34
  • 2
    Yes, via [`String.prototype`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype) and similar. Example: [`.trim()` polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Compatibility). Just note that monkey patching in JavaScript can affect other operations, like `for..in` loops, negatively. – Jonathan Lonowski Jan 25 '14 at 04:08
  • even though i didnt downvote, probably because if you searched your title in a search engine you would have found quite a few pages on prototype. – Patrick Evans Jan 25 '14 at 04:12

1 Answers1

4

The equivalent in JavaScript:

String.prototype.toMagic = function(){ 
   return "magic"; 
}

console.log("".toMagic());//>>> "magic"
Alcides Queiroz
  • 9,456
  • 3
  • 28
  • 43