Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript extensions have built-in objects


May 09, 2021 CoffeeScript


Table of contents


Extend built-in objects

Problem

You want to extend a class to add a new function or replace the old one.

Solution

Use :: Assign your new function to a prototype of an object or class.

String::capitalize = () ->
  (this.split(/\s+/).map (word) -> word[0].toUpperCase() + word[1..-1].toLowerCase()).join ' '

"foo bar     baz".capitalize()
# => 'Foo Bar Baz'

Discuss

In JavaScript (again, in CoffeeScript), objects have a prototype member that defines what member functions can be applied to all objects based on that prototype. In CoffeeScript, you can use :: shortcuts to access the prototype directly.

Note: Although this practice is fairly common in many languages, such as Ruby, in JavaScript, extending local objects is often considered a bad practice (reference: maintainable JavaScript: don't modify objects you don't own; extend built-in local objects). R ight or wrong? /b11>。