Accessing Object's Data Via Another Variable Name - javascript

It's super late and my mind is blanking right now, but let's say I have variable filename and it's storing the name of another variable marker. The variable marker is an array and contains the object & property position: new google.maps.LatLng(42.2550,-114.3221).
I've been stupidly trying to access it via filename.position which of course returns undefined, since it's searching the literal filename for a 'position' property that does not exist.
But how could I pull marker.position by using filename? Is there some nifty jQuery trick for, uh, 'resolving' a variable to its contents? I'm brain fried. I know I've done this before.

If it's possible in your script, you can store the data not just in variable, but in a property of some object (usually it's more convenient to use global one).
For example
var myObj = {};
myObj.marker = new google.maps.LatLng(42.2550,-114.3221); // or anything else
Then you will be able to get this property using a variable like this:
myObj[filename].position
In this case i would also recomment to check for myObj[filename] existance using typeof structure, just to make sure such property exists in myObj.
if (typeof myObj[filename] !== "undefined") {
// do something
}
As apsillers noted, you could use global window object for this as well. But if your marker variable was defined inside some other function (i.e. not global), you won't be able to access it with window.marker or window[filename] as it will be out of scope.
Second way is to use eval() function which i'd strongly recommend to avoid.

Try this :
window[filename].position;

Related

Does it make diffrence in speed efficiency of code if we assign property of object to another variable and then use it?

I wonder does it make difference if I use another variable to access the property of object once and for all or access the data that I want , from the object each time :
data = {position: [{X:12},{Y:4}] ,name : 'Smth'}
is there any diffrent between the following method :
const X = data.position[0].X
for(...){
...do somthing with X
}
or
for(...){
...do somthing with data.position[0].X
}
Yes, some different is exist. Every time when you call property js interpreter try to find calling property (or method) at prototype hierarchy.
Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.
If you use variable to cache some data it will be faster than you use direct access.
There is some great benchmark to test it.

What does "|| {}" mean at the start of a JavaScript file

I am looking at some JavaScript files. Some of them have something interesting at the beginning:
var something = something || {};
Where "something" is clearly a kind of varable name. What does this mean and what does it do? In fact, one file has this and nothing else.
This is a common pattern to make sure a variable exists and if it does not, to set it to a known initial value so it can be used later. In particular:
If the variable something already has a value that is not falsy, this line leaves the value of the variable unchanged.
If this variable something does not have a value, or is falsy, this line sets the value of the variable to {}.
You will see this pattern a lot when adding properties to an object in a script. Let's say you worked for the company Acme and you had a lot of script files to integrate with other people's code. The Acme object would have a bunch of properties and a bunch of functions. In some scripts you might want to add properties to the object. But you can't just say
Acme.TIMEOUT = 300;
at the top of a file because the variable might not exist. But if it does exist, you want to use the existing variable. If it doesn't, you need to create a fresh object first.
So
var Acme = Acme || {};
will guarantee it exists, and then you can use it.
Be careful with this, though. I don't like this pattern because in modern JavaScript (where we use let and const instead of var), having an undefined variable will cause an error to be thrown. You should say:
window.Acme = window.Acme || {};
if you are in a browser. The reason for this is that it makes clear Acme is a property of the window object. Referencing a non-existent property of an object is harmless, you just get undefined. But referencing a non-existent variable will throw an error in modern JavaScript (or if not, it should).
It's a default value for "something" variable.
So if something is not initialized, it will end up containing a blank object (the {}).
in other words something equals (sometging or {}) where undefined evaluates to false so {} is returned.

Reference to a javascript variable in an HTML tag

I am trying to "link" a tag value to a javascript variable (and ideally to a function, but well a variable is a good start), by reference.
I know I can do a myDom.value = myVar but then if the value of myVar change the tag will not be modified.
Is it possible to do this (not using events, because it would be so heavy)?
Thank you :)
No.
You can fake references by assigning objects to things, but only if the property you assign the object to is expecting an object and knows to pull data out of it instead of stringifying it and using it directly.
You could use a closure function around the variable. So instead of attaching the value, you attach a function which will return the variable:
myDom.valueAccessor = function(){ return value }
After this you can access the result as:
myDom.valueAccessor()
This will track the value in value as it changes. Obviously you could choose a snappier name for your function. This seems to work for me in Firefox.

Javascript expando objects

What are expando objects in javascripts?
For what purpose we need this ? Any complete example will be appreciated
I found 1 article here Javascript: The red-headed stepchild of web development
Well, in javascript, any object is an expando object. What it means is, as the article covers, that whenever you try to access a property1 it will automatically be created.
var myObj = {}; // completely empty object
myObj.myProp = 'value';
The moment you assign myProp a value, the property myProp is dynamically created, eventhough it didn't exist before. In a lot of other languages, such as C#, this is not normally possible (actually C# has just enabled expando object support as well, but that's besides the point). To access a property in a normal class in C#, you need to specify in the class that it does indeed have this property.
1 Not quite correct. See npup's comment below for clarification.
Everything except primitive types(string, number,boolean) are objects and support Key:values structure. properties(keys) can be accessed and set using the dot notation as well as the square brackets.
var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // doesn't work, myProp2 is an undefined name.
myObj['myProp2'] = 'value2'; // works , an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string
An article written in 2007 that uses document.all (as the only way to access elements)? That's a big red flag.
It is just dressing up "You can add properties to an object" with some buzzwords.
We need to be able to do this because otherwise we wouldn't be able to store data, and that would make JavaScript a pretty useless language.
(Everything is an array? No it isn't. And it iterates over an object without a hasOwnProperty wrapper. That isn't safe. Just keep away from the article, it is worse than useless)
JavaScript turns elements with specific IDs of names into expandos of the returned DOM object. It is explained here.

jquery object inside an object literal

i am trying not to repeat the selector and get to its children via a the same objects parentElment declared variable.
I tried:
testimonialsBelt={
parentElment:$(".testimonialsCntnr ul"),
childrenElem:this.parentElment.children().length
}
I also tried:
testimonialsBelt={
parentElment:$(".testimonialsCntnr ul"),
childrenElem:$("testimonialsBelt.parentElment").children().length
}
but i keep on getting a undefined when calling alert(testimonialsBelt.childrenElem).
is there anyway to get the jquery object with object literals?
What is the rule? when can i use this and when must i have the full path? (in this case testimonialsBelt.parentElment).
i am trying to have all these variables in one object called testimonialsBelt. i know i can do this with loose javaScript.
Thanks
In object literals, you can only use this to refer to the object that you're declaring inside of a function. Try the following:
var testimonialsBelt = {
parentElment: $(".testimonialsCntnr ul"),
childrenElem: function() {
return this.parentElment.children().length;
}
};
The difference in calling childrenElem is that instead of using alert(testimonialsBelt.childrenElem), you would instead have alert(testimonialsBelt.childrenElem()).
Otherwise, this refers to the current scope that you are in (typically window if you are declaring the object literal as a global).
Addressing your edit: I'm not sure what you mean by "loose javascript," but I assume you mean as simple as possible. In which case, you can try the following, although I'm not a big fan of the method. It's more verbose, but is easy to understand.
var testimonialsBelt = {
parentElment: $(".testimonialsCntnr ul")
};
testimonialsBelt.childrenElem = parentElment.children().length;
This gives you an object where childrenElem is static (it doesn't change) and avoids calling $(".testimonialsCntnr ul") twice. However, if you expect $(".testimonialsCntnr ul").children() to change, then you will need to use my first example.
In JavaScript (not ECMAScript) you can use this:
testimonialsBelt={
parentElment:#1=$(".testimonialsCntnr ul"),
childrenElem:#1#.children().length
}

Categories

Resources