Skip to content
Advertisement

Please explain to me prototypes in javascript using the code below

I am trying to use the prototype method of writing functions that can be implemented by strings to capitalise every first letter of every word. I would like to call this function like,

JavaScript

This is the function I am trying to write:

JavaScript

I had written it this way before:

JavaScript

Advertisement

Answer

I would like to call this function like,

JavaScript

You can’t, strings are immutable. You would have to call it like this:

JavaScript

In your function, you’re using String.prototype incorrectly. String.prototype is the object containing the various String-specific methods. It’s assigned as the underlying prototype of all strings.

Where you’re using String.prototype, you should be using this, and instead of trying to assign to it (this = ... is invalid), return the result.

The simple way to do what you’re doing is to:

  1. Split the string into an array of words, as you have

  2. Loop through that array either building up a new string with the capitalized words via +=, or building a new array with the capitalized words and then doing Array#join at the end to put it back together.

  3. Return the string you built

Something like this:

JavaScript
JavaScript

Note I’ve done away with the check if the array of words’ length isn’t 0: It can’t be 0 if you’ve pre-checked the length as you have.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement