简体   繁体   中英

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?

Yes it's an antipattern. Since js doesn't have native getters and setters which will be crossbrowser, yet, you should create your own getters and setters like:

Obj.prototype.getProp = function () {
    return this.prop;
};

Yes, you still can access this prop directly, but now you doesn't have to. More on that. This way you can create private properties via closures:

function Foo() {
   var __yourPrivateProp = 'Bar';
   return {
           getyourPrivateProp: function () {
               return: __yourPrivateProp
           }
   };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM