2

I have a general question about functions as prototypes on Knockout Objects. Currently, I am having great luck using the following means to extend the prototype of an object, however I'm curious as to what benefits and/or pitfalls I could be running into by doing so.

ko.utils.extend(objectModel.prototype, {
    makeAlert: function() {
        console.log('alert');
    },
    makeWhoopie: function() {
        console.log('whoopie');
    },
});

The other way would be the common js approach

objectModel.prototype.makeAlert = function() { console.log('alert'); }
objectModel.prototype.makeWhoopie = function() { console.log('whoopie'); }

The only other way I've used the ko.utils.extend method was when implementing validations.

Question: Does the knockout utility method for extending prototypes carry with it any additional overhead that would deem unnecessary? Is there a preferred way for this? I do so like keeping my methods separate from my observables.

beauXjames
  • 8,222
  • 3
  • 49
  • 66
  • Have you checked the [source](https://github.com/knockout/knockout/blob/master/src/utils.js#L124-L133) of ko.utils.validation? – nemesv Sep 04 '13 at 19:03
  • Nice link, but that doesn't really pertain to my question. – beauXjames Sep 04 '13 at 19:07
  • Hmm, the "validation" term is misplaced in @nemesv's comment, but the link seems useful: the `extend` method in `ko.utils` looks like it wouldn't carry much overhead at all, answering the first of your two questions. – Jeroen Sep 04 '13 at 20:14
  • Just wanting a consensus on the topic...so far so good. This pattern is working out nicely in terms of closure and brevity on all my ko declarations. – beauXjames Sep 05 '13 at 19:40

1 Answers1

1

Just set up this jsperf test. I'm somewhat surprised by the results to be honest. Keep in mind, though, the difference in performance here is almost negligible, especially when you're only doing it once. I prefer $.extend since it's shorter than ko.utils.extend and I prefer doing the .extend approach because it makes the code more human readable.

So to answer your questions:

Does the knockout utility method for extending prototypes carry with it any additional overhead that would deem unnecessary? Apparently not

Is there a preferred way for this? Matter of opinion. Given the performance difference is negligible, I'd go with the way that is more human readable.

nwayve
  • 2,291
  • 23
  • 33
  • Nice idea with the jsperf run on the various methods. I have many more than one prototype extension in place, so it's be interesting to see the variance in my local environments to see if there would be enough gain in switching over to $.extend from ko.utils.extend. If I get a chance to put together a stronger model for testing against jsperf as you set up, I'll be sure to post it. – beauXjames Sep 09 '13 at 02:16