最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What are practical use cases of javascript prototype objects? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 18

Here 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;
    }
  };
}
发布评论

评论列表(0)

  1. 暂无评论