Extending Prototypes on Knockout Objects

1.7k views Asked by At

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.

1

There are 1 answers

1
nwayve On

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.