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];
Related
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.
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.
This question already has answers here:
What does this documentation syntax mean at MDN for a JavaScript function? [duplicate]
(2 answers)
Closed 7 years ago.
arr.filter(callback[, thisArg])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
So, this is the example in the documentation that I am supposed to understand.
Arr = some array, great. filter = a method the array has, great. callback = some function, basically. Great. What is [, thisArg]though?
Looking at some example on stackoverflow shows this:
objects.filter(function (obj) {
return obj.someIntProp <= 1000
});
I understand how this works, I don't need help using it. I just want to understand how [, thisArg] is supposed to tell me that the function takes each object in an array. I feel like I am missing something obvious that most people get taught in Coding 101.
The thisArg parameter is optional. If you pass it, then when the runtime invokes your callback, it'll set this to whatever that value is.
It's not useful in very many situations, but it's one of those things that is handy when you do want it. An alternative of course would be to bind the callback to whatever you'd pass for thisArg.
The MDN site by convention uses the [, thisArg] notation to mean that the parameter is optional.
It means that the argument is optional. You may or not pass it, the function is valid anyway. If you decide to pass it, then the word this inside that function would access the given value.
This question already has answers here:
Variable name as a string in Javascript
(20 answers)
Closed 9 years ago.
I have a variable as such:
var foo = ["cool", "cool"];
How do I get the variable name, foo, as a string? In other words, given foo, how do I get "foo"? I want to use it in the following context where "foo" is used in getElementById(...):
document.getElementById("foo").innerHTML = document.getElementById("foo").innerHTML + "";
Thanks!
You're looking at this the wrong way round - to answer this question directly
given foo, how do I get "foo"?
Well, the answer is... type "foo" in your code.
You know you want the string representation of the foo variable name when you write your code, so there's no scenario where the string value you want would be anything other than "foo", right?
It's true that you can reference a property foo, for example of the window object, using window["foo"] but that's the other way round too - you have to know it's foo you want, and deliberately use "foo" to get at it. So there's an example - you know what string to use, "foo", at compile time - it couldn't possibly be anything else.
If it's a global variable, you get it as global object property: window in browsers and global in NodeJS. Otherwise, you don't.
This question already has answers here:
Why can't I add properties to a string object in javascript?
(2 answers)
Closed 9 years ago.
Do variables have properties?
The obvious answer should be NO. If I try to assign a property to a variable, it should give an error. Right?
If I do something like:
var someVariable = 'Cat';
someVariable.eyes = 'two'; //Gives no error!
alert(someVariable.eyes); // alerts 'undefined' instead of giving an error!
Variables don't have properties, but their values do. (If the value's an object, anyway.)
In this case, you're trying to set the eyes property of the string currently referenced by someVariable.
It won't work in this case, though. Since primitive values don't have properties, JS will convert the primitive string value into an object and set the property on that object, which pretty much immediately gets silently discarded. The end result: the primitive string remains unmodified.
"Variables" don't actually exist (except strictly within the definition of a scope), only objects. And string objects can't have arbitrary properties assigned by default.