Method that returns property VS property direct access in javascript
I have found that many javascript developers create methods that simply return a property like this :
function Obj (prop) { this.prop = prop; // public } Obj.prototype.getProp = function () { return this.prop; };
While prop is public and can be accessed like this :
var a = obj.prop;
Moreover, I found that accessing an object property with a method is 121 times slower than accessing it directly (in Firefox)
var a, b, obj = new Obj(1); a = obj.prop; // ~6ns on Chrome // ~5ns on Firefox b = obj.getProp(); // ~6ns on Chrome (no difference) // ~730ns on Firefox (122x slower...)
So my question is: should we always create methods that return properties or can we access properties directly? Is that antipattern?
This title and content for this question was made by "neeh" at this link: https://stackoverflow.com/questions/12892849/method-that-returns-property-vs-property-direct-access-in-javascript. Contributions on stackoverflow.com are made under this license.
Javascript
Mobile
Web