It's just another way to create object by some template (or prototype).

Using "your" method: var o = Templater();
Using prototype: var o = new Template(); // see the 'new' keyword

Usage of created object is the same: o._supplant(...);

But also there's few differences in creating derived objects.

Using "your" method:

function DerivedTemplater() {
  var parent = Templater;

  parent.extraMethod = function() {};

  return parent;
}

Using prototype:

function DerivedTemplater() {
}

DerivedTemplater.prototype = new Templater();
DerivedTemplater.prototype.constructor = DerivedTemplater;

DerivedTemplater.prototype.extraMethod = function() {};

It's up to you which method to choose.

Regards,
Max.


On Sat, Apr 9, 2011 at 9:46 AM, planon <spockspla...@gmail.com> 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?
>
> --
> To view archived discussions from the original JSMentors Mailman list: 
> http://www.mail-archive.com/jsmentors@jsmentors.com/
>
> To search via a non-Google archive, visit here: 
> http://www.mail-archive.com/jsmentors@googlegroups.com/
>
> To unsubscribe from this group, send email to
> jsmentors+unsubscr...@googlegroups.com
>

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/jsmentors@jsmentors.com/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/jsmentors@googlegroups.com/

To unsubscribe from this group, send email to
jsmentors+unsubscr...@googlegroups.com

Reply via email to