On Saturday, 9 April 2011 02:46:58 UTC-3, planon wrote:
>
> I was reading Ben Cherry's blog post on Writing Testable Javascript 
> and I came across this example: 
>
> function Templater() { 
>     this._templates = {}; 
> } 
>
> Template.prototype = { 
>     _supplant: function(str, params) { 
>         for (var prop in params) { 
>             str.split("{" + prop +"}").join(params[prop]); 
>         } 
>         return str; 
>     }, 
>     render: function(name, params) { 
>         if (typeof this._templates[name] !== "string") { 
>             throw "Template " + name + " not found!"; 
>         } 
>
>         return this._supplant(this._templates[name], params); 
>     }, 
>     defineTemplate: function(name, template) { 
>         this._templates[name] = template; 
>     } 
> }; 
>
>
>
> http://www.adequatelygood.com/2010/7/Writing-Testable-JavaScript 
>
>
> My question is why does he use prototype to extend this function 
> rather than writing it as: 
>
> function Templater(){ 
>   return { 
>       _supplant:function(){} 
>
>      etc... 
>   } 
> } 
>
> What is the use case for prototype-based extension?
>


I always ask myself when do I really need the Java-like approach in 
Javascript, such as using a constructor function and the 'new' operator, and 
I don't find a reasonable answer to go about writing code in that way.

In your case, I would use a globally available object instead of a 
constructor function:

var Templater = {
  templates: {},

  supplant: function (str, params) {
    var prop;
    if (Object.prototype.hasOwnProperty) { // all browsers except Safari 2
      for (prop in params) {
        if (params.hasOwnProperty(prop)) {
          str.split("{" + prop + "}").join(params[prop]);
        }
      }
    }
    return str;
  },

  render: function (name, params) {
    if (typeof this.templates[name] !== "string") {
      throw "Template " + name + " not found!";
    }
    return this.supplant(this.templates[name], params);
  },

  defineTemplate: function (name, template) {
    this.templates[name] = template;
  }
};

--
JR

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to