Difference between knockout View Models declared as object literals vs functions

In knockout js I see View Models declared as either:

var viewModel = {
    firstname: ko.observable("Bob")
};

ko.applyBindings(viewModel );

or:

var viewModel = function() {
    this.firstname= ko.observable("Bob");
};

ko.applyBindings(new viewModel ());

What’s the difference between the two, if any?

I did find this discussion on the knockoutjs google group but it didn’t really give me a satisfactory answer.

I can see a reason if I wanted to initialise the model with some data, for example:

var viewModel = function(person) {
    this.firstname= ko.observable(person.firstname);
};

var person = ... ;
ko.applyBindings(new viewModel(person));

But if I’m not doing that does it matter which style I choose?

2 Answers
2

Leave a Comment