like this code
var Obj = function () {}
Obj.prototype.getVarName = function () {
console.log( someFunction() );
}
var obj = new Obj();
obj.getVarName(); //output "obj";
var obj1 = new Obj();
obj1.getVarName(); //output "obj1";
and i don't want to do it in this way
var Obj = function (variableName) {
this.variableName = variableName || "undefined";
}
Obj.prototype.getVarName = function () {
console.log(this.variableName);
}
var obj = new Obj('obj');
obj.getVarName(); //output "obj";
var obj1 = new Obj('obj1');
obj1.getVarName(); //output "obj1";
someone has any idea to do with this problem,thanks.
p.s:I was doing something in somg incorrect way.so I ask this Unanswered question,thanks all guys.
I bing an event to an DOM elem by a class obj's method ,and this obj has somg child class obj,when trigger the event,this varialbe is point to the dom elem,any I don't know how to recognition which obj trigger this event,so i try this way.
But it's a wrong way!So i try it by some other method.I use the call method to change the this variable,and now i solve my problem.
I believe the answer is "it can't be done".
Variable labels aren't meant to be looked at by your code at run-time. They're meant for you, as the program author, to be used at program write-time.
If an Object needs a label that you need to examine and use at run-time you should give it that property to use.
someObject.myName = "someObject"; // if that's what you really want
There's simply no relation from an object to the variable holding it as value.
Because there can be more than one variable.
var obj = new Obj();
var obj2 = obj;
obj2.getVarName(); // what do you want ?
That's one of the basis of the concept of variable in probably all programming languages. You won't change that. if you want your objects to have a name, the solution is to give them a name, not using the variable names.
What dystroy and Genia S. said.
Your code smells BAD. Why are you trying to do this?
The way you don't want to do it actually looks like the best option, i.e. create an object with a name field.
Related
When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];
I'm trying to create an object where there is a key value pair, and the value is an array.
i.e:
foo = {'key1':['val1','val2'], 'key2':['v3','v4']};
Is this possible in pure JS?
e.g.
var foo = {};
foo['key1'] = ['keyOneVal1'];
foo['key1'] = ['keyOneVal2'];
but as you may have guessed, this just overwrites the keyOneVal1.
I've also tried
var foo = {};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
but couldn't get it working in a jsfiddle.
EDIT:
Okay heard you guys loud and clear.
This object will not be initialized with an starting key, it's dynamically inserted based on time. So in the end the object will look more like
foo = {'time1':['a','b'], 'time2':['c','d','e','f'], 'time3':['y','y']};
It's very possible. Your second example is the correct way to do it. You're just missing the initializer:
var foo = {};
foo['key1'] = [];
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
for(var i = 0; i < foo['key1'].length; i++) {
document.write(foo['key1'][i] + '<br />');
}
Try something like this make sure you declare key1:
var foo = {"key1" : []};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
It can be done like this
var foo = {"key":[]}
foo["key"].push("val1")
foo["key"].push("val2")
I've got a bit of a problem here. I've got the following code declaring two variables:
var anawesomevariable = "hello world";
var variabletwo = "anawesomevariable";
As you can see, the second variable's contents are the same as the name of the first variable. My problem: I want to change the first variable using the contents of variabletwo. So in other words, I want to say "Hey Javascript, change the contents of the variable whose name is in variabletwo". Is there any way to do this in Javascript?
P.S. I havn't really explained that clearly, but you get my point (I hope)
You can do
eval(variabletwo + ' = "new value"');
which results in running the code
anawesomevariable = "new value";
If awesomevariable is a global variable you can do this:
window[variabletwo] = 'goodbye world';
You cannot* (and should not) manipulate variables, but it's a piece of cake with properties:
var obj = {anawesomevariable: "hello world"};
var variabletwo = "anawesomevariable";
obj[variabletwo] = whatever
^* don't even think about "eval" here. seriously.
You have a few options. Option 1, which uses eval(), which I discourage, would be simplest, like this
eval(variabletwo + ' = "cool"');
The second option is to declare them as globals, like this
window.anawesomevariable = "hello world";
window.variabletwo = "anawesomevariable"
and then
window[variabletwo]="foo";
However, if you want to keep something in the current scope, declare it in an object, like this
var obj = {anawesomevariable: "hello world"};
var variabletwo = "anawesomevariable";
obj[variabletwo] = "foo";
I want to create a log function where I can insert variable names like this:
var a = '123',
b = 'abc';
log([a, b]);
And the result should look like this in the console.log
a: 123
b: abc
Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.
so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:
["123","abc"];
and nothing more
you could provide the function the names of the variables and the scope they are in, like:
function log(arr,scope){
for(var i=0;i<arr.length;i++){
console.log(arr[i]+':'scope[arr[i]]);
}
}
however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:
for nonstrict functions, this is window
for strict functions, this is undefined
for constructor functions, this is the constructed object
within an object literal, this is the immediate enclosing object
so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.
if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.
I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.
console.log({a:a, b:b});
If you really prefer the format that you already illustrated, then you can do it like this:
function log(o) {
var key;
for (key in o) {
console.log(key + ":", o[key]);
}
}
var a = '1243';
var b = 'qwre';
log({
a:a,
b:b
});
Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.
Something like this would do what you're looking for:
function log(logDict) {
for (var item in logDict) {
console.log(item + ": " + logDict[item]);
}
}
function logSomeStuff() {
var dict = {};
dict.a = "123";
dict.b = "abc";
log(dict);
}
logSomeStuff();
Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:
function MyLogObject(name, value) {
this.name = name;
this.value = value;
}
var log = [];
log.push(new MyLogObject('a', '123'));
log.push(new MyLogObject('b', 'abc'));
for each (var item in log) {
if (item.value != undefined)
alert(item.name + "/" + item.value);
}
Then you can loop thru this Object and you can get the name and the value
You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:
var x = 7;
var y = 8;
function logVars(arr){
for(var i = 0; i < arr.length; i++){
alert(arr[i] + " = " + window[arr[i]]);
}
}
logVars(["x","y"]);
I had a somewhat similar problem, but for different reasons.
The best solution I could find was:
MyArray = ["zero","one","two","three","four","five"];
MyArray.name="MyArray";
So if:
x=MyArray.name;
Then:
X=="MyArray"
Like I said, it suited my needs, but not sure HOW this will work for you.
I feel silly that I even needed it, but I did.
test this.
var variableA="valor01"; <br>
var variableB="valor02";
var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>
console.log(NamevariableA,NamevariableB);
atte.
Manuel Retamozo Arrué
I have an object within an object. It looks like this.
var myLib = {
object1: {}
}
My basic problem is that I wanted to end up like this. So I would like to do this dynamically I will not know the property's or additional objects until run time.
var myLib = {
object1: ({"A1":({"Color":"Blue",
"height":50})
})
}
From reading here on Stack Overflow I know that I can create an object within an object by simply going like this:
myLib.Object1["A1"] = "Something"
But this does not produce what I'm looking for.
I tried this syntax which I know is wrong but basically
mylib.Object1["A1"].["color"]="Blue";
so basically here is the question. I would like to create object "A1" under "mylib.Object" and immediately add property color = "blue" to "A1". I would need to do this for several other properties, but if I can figure out how to do this for one, I can figure it out for the rest. How can I accomplish this task?
No jQuery, please. Just plain old JavaScript is what I'm looking for.**
Once I create the object and properties I would imagine I can just use a for loop to loop through the properties for that object. Like so:
for(key in mylib.Object1["A1"]){}
Right?
You can create it all from scratch like this:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
myLib.object1[x] = {Color: "Blue", height: 50};
Or, if all values are in variables:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
var colorProp = "Color";
var colorPropValue = "Blue";
var heightProp = "height";
var heightPropValue = 50;
myLib.object1[x] = {}; // create empty object so we can then add properties to it
myLib.object1[x][colorProp] = colorPropValue; // add one property
myLib.object1[x][heightProp] = heightPropValue; // add another property
These syntaxes create identical results:
myLib.object1.A1 = {};
var x = "A1";
myLib.object1[x] = {};
The first can only be used when the property name is known when you write the code and when the property name follows the proper rules for a javascript identifier. The second can be used any time, but is typically used when the property name is in a variable or when it doesn't follow the rules for a javascript identifier (like it starts with a digit).