Question

According to the Google style guide, methods should be defined on the prototype of a constructor and properties should be defined in the constructor using the this keyword.

I do most of my front end development using Knockout, which handles observing properties by turning them into functions. That is, all of my properties are now methods, more or less. Is this a significant performance hit? Are there any Knockout workarounds using JavaScript getters and setters?

Was it helpful?

Solution

So first, yes there is a plugin for knockout that uses getters and setters, but it only works in newer browsers. You sacrifice compatability to IE8< (this is unavoidable, since those browsers do not support javascript getters/setters). The plugin can be found here.

To your main point: understanding the style guides intent is important. Because methods are usually reusable, putting them on the prototype saves duplicated code and memory allocation. This is why it is a recommendation to put them on the prototype. However, knockout observables are not reusable. They behave like properties: they store information specific to an instance. This difference is important. They may be functions, but they are treated like properties.

The Google style guide simply does not address this scenario. It is not a performance hit to place them on the instance, because you are comparing it to a scenario that will not work. Placing observable's on the prototype will break the model. It isn't a performance hit to do the only thing that works.

As a final note, the getters and setters plugin doesn't make the functions disappear, it just hides them behind the getter and setter. Performance will not improve, because the same work still has to be done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top