Best approach to avoid naming collisions in object with javascript [duplicate] - javascript

This question already has answers here:
Is the underscore prefix for property and method names merely a convention?
(6 answers)
Closed 2 years ago.
Lets say I have an object with a getter and a setter.
const obj = {
a: 0,
get a(){
return this.a;
}
}
I would get an error Maximum call stack size exceeded at Object.get a [as a]. I could name the a variable something different but then it gets confusing after a while.
I could prefix it with an underscore or something like this:
const obj = {
_a: 0,
get a(){
return this._a;
}
}
I was wondering if there is an industry standard for handling this? Is using underscores not the right approach because they are symbolic of other things? What is the recommended approach for handling this or is it one of those things that is up to the developer?
I just don't want to go down the path of doing this the wrong way and can't really find a definitive answer on the matter.
Thanks.

Your first example doesn't work, because the getter named a will end up being the only property on your object. When you call this.a you're actually calling the getter again and so you end up with a stackoverflow.
Using _ as prefix for underlaying variables is perfectly fine. This actually lines up with other languages.

Related

Turn a string into function in JS [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
My problem is simple and I couldn't find the proper answer in this forum. My bad...
I want to do that :
const dataReceived = foo;
foo(state);
How can I do that?
I read it is better to avoid eval, and I couldn't get success with new Function.
Thanks for your help!
EDIT
Thanks for your answers.
I work with React.
In my reducer, I have a create_item case.
I can reach action.category, that can be the word 'currency' or 'country'.
What I want to do is to launch either the method createCurrency or createCountry according what is inside action.category.
That's why I tried to join 'create' and 'action.category' to create a dynamic function name.
But it seems to be a poor idea...
The simplest approach is to create an object which contains an entry where:
the key is a string
the value is a function.
Example:
const myObject = {
myFunction: () => { [... DO SOMETHING...] }
}
Subsequently you will be able to invoke the function, using:
myObject.myFunction();
The above becomes more powerful when you use brackets notation.
Example:
const myString = 'myFunction';
myObject[myString]();

Why do we need to use the THIS keyword in this example? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 2 years ago.
I'm a beginner and following a long from a udemy course and I've come across this example where we use the THIS keyword to reference the properties within it's object. However, I don't understand why we can't just grab the property like we would normally do when we are outside of the object by doing: objectname.property. I tested it and it seems to work fine. I'm obviously missing something so if someone could let me know that would be hugely appreciated! The example is below. Instead of using this, why not just use mark.bmi for instance.
const mark = {
name: `mark`,
mass: 92,
height: 1.95,
bmiCalc: function() {
this.bmi = this.mass / (this.height * this.height);
return this.bmi;
}
}
Properties can be added dynamically to an object. You presented a trivial case, but in most of the cases, the compiler would not be able to decide without a "this." if you reference a member of the current object, or some global variable
Change the variable name mark to jacob, you don't need to refactor. But if you had changed this to mark then you needed to change it also to the new variable name.
Usually you create more objects (or instances) from a class. The method defined in the class applies to more than just this object (mark). That's the reason for using this in object oriented programming.

Variables as 'literals' [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 9 years ago.
I am wondering whether I can use variables that I pass to a function as arguments as "literals" (I don't know a better way to describe the problem, perhaps the example will clear things up):
banana = yellow;
minion = cute;
function ex(banana, minion) {
banana.minion;
}
// What I want is: yellow.cute
Edit
I think I might not have been asking exactly what I meant. I'm sorry for that. Here's the actual code that might clarify things.
function ex(banana, minion){
createjs.Tween.get(banana, {override: true}).to({banana: minion}, -(value + -banana.minion) * speed, createjs.Ease.ease);
console.log(banana); // returns 'yellow'
console.log(minion); // returns 'cute'
console.log(banana.minion); // returns 'undefined'
console.log(banana[minion]); // returns 'undefined' too
}
So I want to pass whatever I define as banana or minion to be 'literal', so that it will read createjs.Tween.get(yellow, {override: true}).to({yellow: cute}, -(value + -yellow.cute) * speed, createjs.Ease.ease);
You can pass the name as a string and use the array syntax to access the property.
function ex(banana, minion) {
return banana[minion];
}
If you want the left hand side of an object to be a string as well (e.g. banana, you could use eval(banana)[minion] but that might raise a few eyebrows at a code review. Note that this works for both properties and methods e.g. eval(banana)[minion](), though I'd step back a bit and ask why you need to do this kind of moderately bonkers stuff :)
Use bracket notation instead of dot notation as the member operator
ex
banana[minion];

Can you set an undefined variable as a function parameter? [duplicate]

This question already has answers here:
Undefined variable as function argument javascript
(2 answers)
Closed 8 years ago.
I am building a function to match types of variables. It will be an alternative to typeof <var> === "something".
My function call looks like this : is("some text")["string"]. It returns true, or is([])["element"]. Now it returns false, But I have an issue with it.
For example, if I try to send an undefined variable like "undefVar" to a function I am expecting something like this: is(undefVar)["undefined"], but I get an error which says that "undefVar" is not defined.
Can I somehow make my function work using undefined variables? Is this possible at all?
p.s: I have to use this function a lot so it seems (for me) that it would be better to use something like this : is(var)[type] as opposed to typeof var === type.
typeof is special on nonexistent variables. You cannot mimic it with a function.
No, you cannot blindly pass undefined variables to your function from the call site and globally change the behavior of the JS engine to accomodate this.
typeof is a built-in operator and is not bound by the rules of "common" functions, which is why it can do things that custom functions cannot.
Finally, I strongly disagree that it would be practically preferable to use an alternative syntax even if that were possible.

What is the difference between Something.prototype.else and Something.else [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: Class.method vs. Class.prototype.method
I am trying to understand object in JavaScript. Now I see a lot of different uses of object, and I can not tell them apart.
For starters, the biggest thing I want to know is what the difference is between these two
Something.prototype.else = function(){
return 6;
}
And
Something.else = function(){
return 6;
}
Both look different, but they are used in the same way, or am I mistaken.
If you are familiar with other programming languages you can consider the second one to be a static method.
The first one you need an instance of the object in order to use it:
var x = new Something();
x.else();
The second one you do not need an instance in order to use it:
Something.else();
It's a good question for an interview for a JavaScript job indeed.
The difference is that Something.else overrides Something.prototype.else. That is, if you have both, Something.else will be used.
The advantage of having prototypes is that a prototype can be shared between many objects to reduce memory usage, make monkey-patching easier and implement prototype-based inheritance.

Categories