Getters & Setters vs Property access

Getters & Setters vs Property access
0.0 0


Consider the following:

`SomeClass = cc.Node.extend({


    this._someVar = value;
   return this._someVar;


then somewhere in my code I have a SomeClass object…

var aObj = new SomeClass(); aObj._someVar = 5; aObj.setSomeVar(5);

is there any difference bettwen direct access of the property or using a setter?


I think the variables can’t be private in javascript, so this is why you see them, but you should use setters to avoid strange behaviours (a setter could do additional actions in some cases, not just changing the value of such “associated” variable)


I think using a setter is better than direct access of the property when we access property outside the class.

Because we can add some logic to the getter/setter.

For example, there are some codes in CCNode.js:

`setPosition:function (newPosOrxValue, yValue) {
var locPosition = this._position;
if (arguments.length == 2) {
locPosition.x = newPosOrxValue;
locPosition.y = yValue;
} else if (arguments.length == 1) {
locPosition.x = newPosOrxValue.x;
locPosition.y = newPosOrxValue.y;

getPosition:function () {
    return cc.p(this._position.x, this._position.y);


>I think the variables can’t be private in javascript

Not completely true, you can achieve private variables through closure, though cocos2d-html5 doesn’t leverage this so I probably wouldn’t either.


My only concern is performace. Are there any performance issues?

I really don’t want to write getters and setters for every property that I have…


There is probably an oh so slight performance hit to having getters/setters but it would be so insignificant that it shouldn’t play a factor in your consideration.

There are very valid reasons to setting a getter/setter to every property. You don’t need to track which properties you manage via direct access or by getter/setter. If someone else comes on to this project with you then they know that ALL properties are access the same way (including the same way as the cocos2d-html5 framework that you are using), If you have to leave the project for some extended period of time and come back, it’ll be easier to get back into since all properties are handled the same way. You don’t have to worry about accidentally accessing a property directly when you should have used a getter/setter for the logic contained in the functions. It’s easier to later decide that logic is needed to getters/setters since they exist and you can just add it instead of adding the function and going through the rest of your source changing all the direct accesses to getters/setters.

I’m sure I can come up with more :).


C.J. thats very true.

I will take your advices into consideration and spend some more time writing getters and setters :slight_smile:

I just wanted to know if there were any technical issues…

Thanks folks!