Javascript Naming Convention: value() vs getValue() [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
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.

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.

Related

I do not understand the function [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I do not understand the function fromToFn(),
in my example there is no function with that name,
I do not understand my example
Example:
var fromTo = function fromTo(i,limit){
return function(){
var next = i;
if(i<limit){
i += 1;
return next;
}
return undefined;
}
}
var collect = function collect(fromToFn,array){
return function (){
var value = fromToFn();
if (value !== undefined){
array.push(value);
}
return value;
}
}
var array = [];
var col = collect(fromTo(0,2),array);
col(); //returns 0
col(); //returns 1
col(); //returns undefined
console.log(array); //returns [0,1]
I do not understand the function fromToFn(), in my example there is no function with that name
That's true, but it doesn't matter. Functions are first-class objects in JavaScript, references to them can be passed around in variables, properties, and parameters.
fromToFn is the name of a parameter in the collect function:
var collect = function collect(fromToFn,array){
// ----------------------------^
So if we pass a function into collect, we can use it within collect via that parameter.
The code does pass a function into collect, here:
var col = collect(fromTo(0,2),array);
...because fromTo(0, 2) returns a function, which is then passed into collect. To be very clear, because there are a couple of things going on, the function being passed into collect is not fromTo, it's the function fromTo returns. That line can be written:
var functionToPassToCollect = fromTo(0,2);
var col = collect(functionToPassToCollect,array);
Here's a simpler example demonstrating using a parameter to call a function passed in:
function example(f) {
f();
}
function callMe() {
console.log("callMe was called");
}
example(callMe);
When you do
var col = collect(fromTo(0,2),array);
You're calling the collect function and the first argument you pass is fromTo(0,2).
The fromTo function, when called, returns a function. So fromToFn, in the call to collect, is a function and can be called too:
var value = fromToFn();
fromTo and collect handle functions, they're called "higher-order" functions. This is possible in JavaScript because in JavaScript functions are first-class values, they can be assigned to variables like other types of values (see First-Class functions).
In this specific case, the point of the function returned by fromTo is that it can uses the variables of the fromTo scope, it's called a closure.
fromToFn is the function that sent to the 'collect' function as parameter :
function collect(fromToFn,array);
and you send the fromTo function :
collect(fromTo(0,2),array)

Why are methods like setters used, instead of changing properties directly in Javascript? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
With an object defined.
var bob = {age: 10};
Defined setter as:
bob.setAge = function (newAge){
bob.age = newAge;
};
So we can change a property as:
bob.setAge(20)
Instead of simply:
bob.age = 20;
or
bob["age"] = 20;
Is best practices the reason?
Because this allows to hide and save the state of the object against unwanted side effects
bob.setAge = function (newAge){
bob.age = newAge || 0; // age must never be undefined or null;
};
You have to wrap everything in a module/closure/function to actually hide the fields which carry the object's state.
var user = (function () {
var name = '';
function getName() {
return name;
}
function setName(value) {
if (!value) {
console.warn('setName: empty value passed');
}
name = value || '';
}
return {
getName: getName,
setName: setName
};
}());
// undefined, the variable could not be resolved
console.info(user['name']);
user.setName('Sergio Prada');
console.info(user.getName());
// warning
user.setName(null);
// empty string, undefined or null will never be returned
console.info(user.getName());
For getters, it allows for validation checks to be applied to make sure that only correct values will ever be set.
As well as this, you can encapsulate the internal method of storage for the variable. For example, you might encrypt the data if you're storing it in the database, but decrypt in the getter so it's automatically ready

Define 'this' keyword in a variable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a function in the following format:
var obj = {
doSomething: function(){
this.callSomething();
},
callSomething: function(){
this.doThis();
this.andDoThis();
},
doThis: function(){
if(!this.bln){
this.bln = true;
}
// some code here
},
andDoThis: function(){
if(this.bln){
// some code here
}
}
}
obj.doSomething();
As you can see in the above code, I am using this keyword many times to call a function or a obj scoped variables.
Instead of using this keyword, I want to use something of single letter like:
var s = this; // so that I can use "s" instead of "this" everywhere
How can I do this?
PS: Here obj object name is just for example purpose. In real scenario, the object name is longer than this keyword.
You can get rid of this entirely if you use the module or the revealing module patterns.
The following example uses the revealing module pattern:
var module = (function() {
var bln = false,
doSomething = function() { callSomething(); },
callSomething = function() { doThis(); andDoThis(); },
doThis = function() { if (!bln) { bln = true; } },
andDoThis = function() { if (bln) { /* do stuff */ } };
return {
doSomething: doSomething //Only public method, rest are private
};
})();
module.doSomething();
Try this. Variable name itself can be used as this inside that object.
var longName = s = {
doSomething: function(){
s.callSomething();
},
callSomething: function(){
s.doThis();
s.andDoThis();
},
doThis: function(){
if(!s.bln){
s.bln = true;
}
// some code here
}
...........................
}
Hi probably the above answers are correct, BUT its not a good way to do things.
It will be way harder to read your code if you go away from "this". Reading "this" you always know you are talking about the reference of your object instance.
The only reason i can think of where this could be usefull is to reduce memory by 3 byte for each "this" you replace by "s".
You would have to define s on a global scope to achieve what you actually want - which is VERY dangerous.
There is alot of blackboxing you do in javascript by implementing eg. frameworks that might ruin everything for you.

Returning function vs returning object [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
In javascript, there are two patterns and I would like to weight the benefits of using one vs the other. What is the difference between returning an object vs returning a function, for example:
var returnFunction = function(name,age){
var n = name;
var a = name;
return function(){
anotherFunc : function(){},
oneMoreFunc : function(){}
}
}
I returned a function containing two more functions, and access to private variables name and age. I understand that I can invoke returnfunction, and I know that I can use it like a constructor. I want to know, what are the benefits of this style vs:
var returnObject = function(name,age){
var n = name;
var a = age;
return {
anotherFunc:function(){},
oneMoreFunc:function(){},
};
}
Is there a performance penalty?
Is it just a matter of style?
Are there any benefits to one or the other, or am I just overthinking this?
edit:
With regards to option A, I was referencing this particular syntax from Javascript: The Good Parts
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
String.method('deentityify', function() {
// The entity table. It maps entity names to
// characters.
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
// Return the deentityify method.
return function() {
// This is the deentityify method. It calls the string
// replace method, looking for substrings that start
// with '&' and end with ';'. If the characters in
// between are in the entity table, then replace the
// entity with the character from the table. It uses
// a regular expression (Chapter 7).
return this.replace(/&([^&;]+);/g,
function(a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
Option A was a contrived example meant to replicate this syntax.
Variant A doesn't work. It's a syntax error.
So what you're really comparing:
var returnFunction = function(name,age){
var n = name;
var a = name;
// return a function that returns
return function(){
// logic to construct the object
var obj = {
anotherFunc : function(){},
oneMoreFunc : function(){}
}
// return the object
return obj;
}
}
// vs.
var returnObject = function(name,age){
var n = name;
var a = age;
// return the object directly
return {
anotherFunc:function(){},
oneMoreFunc:function(){},
};
}
It depends on what does the object look like.
In most cases, you'd go with option B. Just return a simple object.
I don't know anything other than V8, but in V8 it looks like this:
-> new scope
-> assign some vars
-> create a function
-> compile the code in that function
-> return the function, close the scope
-> run the function
-> new scope
-> create the object
-> return the object, close the scope
vs.
-> new scope
-> assign some vars
-> create the object
-> return the object, close the scope
Obviously the first has more steps, but the speed difference is insignificant.
However, there are cases in which it would simply be impractical to return a complex object with multiple nested properties and native functions that have to be initialized. Case in which it is much more useful to generate the object and return it on-a-need basis. Which is option A.
But, better than having option A, and if you intend to make interventions on that returned object, it's just nicer to make it a class:
var returnObjectClass = function(name,age){
this.name = name;
this.class = class;
this.anotherFunc = function(){};
this.oneMoreFunc = function(){};
return this;
}
You can read more here: http://www.phpied.com/3-ways-to-define-a-javascript-class/

JS/Jquery variable schange event [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
detect variable change in javascript
How can i found out that my variable has changed?
I have an event that performed every time when my variable is for example == 1, i want it to perfome only when my variable changes.
You can do that via a property setter, which is a newly-standardized part of the language (new as of the ECMAScript5 specification). That will only work for a property defined with a setter on an object, not with any old variable or property.
Here's an example of an object with a foo property with both a getter and a setter:
var obj = {};
Object.defineProperty(obj, "foo", (function(){
var value = 42;
function fooGet() {
display("Getting: " + value);
return value;
}
function fooSet(newValue) {
display("Setting: " + newValue);
value = newValue;
}
return {
get: fooGet,
set: fooSet
};
})());
Live example, but only works on browsers with support for ECMAScript5 properties, which I think is just Google Chrome at the moment
Or of course, just directly use getter and setter functions rather than properties. :-)
Simple: Don't use a primitive variable but an object which has a "setter" method to change the value. In the setter, you can call additional code.
You can't do this with primitives. The only way it would be possible is if you encapsulated the variable in an object, and added some custom events to this object.
#T.J. I think #Aaron is suggesting an object that does something like this:
var myVar = new Watched(1, function (newValue) { alert(newValue) });
myVar.add(2); // alert(3);
myVar.add(10); // alert(13)
Where Watched maintains an internal value that is updated by methods, which fire a callback to say they have updated.
EDITED:
Ok maybe not what #Aaron was thinking:)
I had something very simple like this in mind:
function Watched (initVal, cb) {
var value = initVal;
function add (val) {
value += val;
cb(value);
}
// return public methods
return { add: add };
}
You could use the setInterval method to periodically check the variable's value and do your stuff if it's what you want.
It's not a nice solution, though. The other suggestions are better.
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
EDIT:
var myVar = 0;
var intervalId = setInterval('checkVariable(myVar);', 3000);
function checkVariable(theVar) {
if (theVar == 1) {
alert('Variable is 1.');
}
}
That will execute checkVariable(myVar) every 3 seconds.

Categories

Resources