Imagine a simple object:
function createObj(someValue) { return { someFunction: function () { return someValue; } }; }; It basically does:
var obj = createObj("something"); var result = obj.someFunction(); // "something" Now, someFunction refers to a function that returns a value. What should be the correct naming convention used in javascript for the someFunction function? Should it be named as what it does? Or its ok to name it with the name of the object that it returns?
I mean, should I name it value(), or should I name it getValue()? Why?
Thanks in advance.
44 Answers
There's no "correct" naming in JavaScript. However, there are three conventions that are mostly used:
Independent getter and setter:
In this approach, we create both a getter and a setter functions, like in Java:
var value; this.getValue = function () { return value; } this.setValue(val) { value = val; } Combined getter/setter method
In this approach, you have a single method that does both. The magic here is that it checks whether you provides a new value for your property:
var _value; this.value = function (val) { if (arguments.length > 0) { // Acts like a setter _value = value; return this; } return _value; } It's also common to define your setter to return the actual instance of your class, so you can do this:
myObj .setProp1("foo") .setProp2("bar"); Object.defineProperty
This one is less used, but it's also an option. It's similar to Objective-C @property statement:
var _value; Object.defineProperty(this, "value", { get: function() { return _value; }, set: function(val) { _value = val; } }); Then you can access it like if it was a public property:
console.log(myObj.value); // Calls the getter method myObj.value = newValue; // Calls the setter method General naming conventions say getValue() would be the name of a function, where value would be the name of the variable.
So, if you were accessing the data directly, you would use obj.value, whereas if you were using a function to get some data, you would use obj.getValue().
There are quite a few naming conventions out there for Javascript in particular.
This question has a sister and hopefully this will help with your question: Clicky for more info
I am personally a fan of getValue and setValue but when reading other peoples codebase, i have seen
object.value = function(item){ if (!item) return this.value; this.value = item; } jQuery uses this on the regular, which is why i don't want to necessarily bash on it.