How are you using javascript prototype objects in your everyday code? I found it hard to either explain or find use cases for it.
Purpose driven examples and pseudo code examples would be great - thanks!
How are you using javascript prototype objects in your everyday code? I found it hard to either explain or find use cases for it.
Purpose driven examples and pseudo code examples would be great - thanks!
Share Improve this question edited Sep 13, 2010 at 19:38 meow asked Sep 13, 2010 at 17:59 meowmeow 28.2k36 gold badges121 silver badges178 bronze badges 2- 4 I am not sure what you mean. The whole language is designed around the use of prototypes. – ChaosPandion Commented Sep 13, 2010 at 18:01
- Are you asking for examples of the use of prototypes where classes couldn't work as elegantly? – strager Commented Sep 13, 2010 at 18:11
1 Answer
Reset to default 18Here is a very simple example. Wouldn't be nice if String had a trim() function so you could do this?
var x = " A B C ";
var y = x.trim(); // y == "A B C"
Well, it can. Just put this at the beginning of your code:
if (!String.prototype.trim) {
String.prototype.trim = function() {
try {
return this.replace(/^\s+|\s+$/g, "");
} catch (e) {
return this;
}
};
}