Skip to main content

Javascript Prototype

Resources

Questions

Q: Create “native” methods

  • define a repeatify function on the String object
    • function accepts an integer for how many times the string should repeat
    • returns the string repeated the number of times specified
    • 'hello'.repeatify(3) => hellohellohello
String.prototype.repeatify =
String.prototype.repeatify ||
function (times) {
var str = '';

for (var i = 0; i < times; i++) {
str += this;
}
return str;
};

Call "hello".addCommas() and have it put commas between every letter

String.prototype.addCommas =
String.prototype.addCommas ||
function () {
return [...this].join(",");
};

console.log("hello".addCommas()); // "h,e,l,l,o"


// Last comma removed
String.prototype.addCommas2 =
String.prototype.addCommas2 ||
function () {
const arrayWithCommas = [...this].join(",").split("");
arrayWithCommas.splice(arrayWithCommas.lastIndexOf(","), 1);
return arrayWithCommas.join("");
};

console.log("hello".addCommas2()); // "h,e,l,lo"

Question is testing

  • knowledge of inheritance in JavaScript and the prototype property
  • ability to extend native data type functionalities (although this should not be done)
  • bonus for not overriding previously defined functions
    • testing that the function didn’t exist before defining your own