How to know the name of a variable in JavaScript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get variable name. javascript “reflection”
Is there a way to know the name of a variable?
Example:
var a = 1;
var b = 4;
function getName(param){
//What should I return here?
}
What I want to do, is to have getName return "a" if I call getName(a)and return "b" if I call getName(b)
Is this possible?

No, that's not possible in a clean way and I highly doubt there is a useful use-case for this.

You could alter the prototype of the object to add a function to do this, as described in this StackOverflow answer:
Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};

It isn't possible to get variable name. But you can get name of variable, who got exactly this value (if you got some vairables with equal values, you get first defined). And this function works only for global variables.
var a = 1;
var b = 4;
function test(value) {
for (var x in window)
if (window[x] === value)
return x;
}
alert(test(b));

Related

JavaScript: Is it possible to declare a variable using another variable's value? [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 1 year ago.
Here is an example of what I'm trying to accomplish:
const a = 'name';
const ${a} = 1;
The second variable should be:
const name = 1;
Is this possible? Thank you in advance.
Could use an object though, something like
var obj;
var x = "name";
obj[x] = 1;
console.log(obj[x]);
const a = 'name';
eval (a + " = 37");
This will create a variable name with the value 37.
However, I prefer Nobel Eugene's solution as a better approach to the problem.

Javascript Function with String/Object attached to it [duplicate]

This question already has answers here:
Add method to string class
(6 answers)
Closed 4 years ago.
In javascript, I want to write a function which is called as follows:
var x = 'testString'
var y = 'anotherstring'
var z = 0
var result = x.aFunction(y, z)
function aFunction(y, z) {
...
}
This is the first time I am attempting this, my question is how can I get and use the value of x in the function aFunction, without actually referring to the declared variable.
I tried looking for this but I cannot find anything. If there is a post specifically for this that anyone knows about, please let me know.
Thanks
You need to use String.prototype.aFunction so that you can add a custom function aFunction() to the prototype of String such that it can be invoked by a string variable. Also this.toString() inside the prototype function will give you the value of the x variable (calling string)
var x = 'testString'
var y = 'anotherstring'
var z = 0
String.prototype.aFunction = function(y, z){
console.log(this.toString());
return y+z;
}
var result = x.aFunction(y, z);
console.log(result);

Define object by a variables string [duplicate]

This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Using a variable value to call an array element
(7 answers)
Closed 8 years ago.
Hard to explain.. I basicly want to do the following:
var doWhat = "speak";
var speak = {
hello: function() { alert: "Hello!"; }
};
// Won't work
doWhat.hello();
It's a bad example, but you should be able to get what I mean.
Is it possible somehow ?
You can use eval(doWhat).hello();. That way the contents of doWhat will be evaluated to the object reference.
You can do something like
var doWhat = {}, str = "speak";
doWhat[str] = {
hello : function() {}
};
doWhat[str].hello();
jsName = 'PageIndexController';
//ST1
eval("if( typeof jsName === 'undefined')alert(111);");
//ST1
eval("if( typeof " + jsName + " === 'undefined')alert(222);");
//ST1 not work
//ST2 work and the output: 222;
//there are two different way using eval, we will get 2 different outcome.

In JavaScript, is there an easier way to check if a property of a property exists?

Is there an easy way to natively determine if a deep property exists within an object in JavaScript? For example, I need to access a property like this:
var myVal = appData.foo.bar.setting;
But there is a chance that either foo, foo.bar, or foo.bar.setting has not been defined yet. In Groovy, we can do something like this:
def myVal = appData?.foo?.bar?.setting
Is there a similar way to do this in JavaScript, without having to write a custom function or nested if statements? I've found this answer to be useful, but was hoping there was a more elegant and less custom way.
I find this very convenient:
var myVal = (myVal=appData) && (myVal=myVal.foo) && (myVal=myVal.bar) && myVal.settings;
If a property exists, the next part of the sequence will be attempted.
When the expression before && evaluates to false, the next part of the expression will not be checked. If either of myVal.appData.foo.bar.settings is not defined, the value of myVal (undefined( will evaluate to false.
Sorry, it's not great:
var myVal = appData && appData.foo && appData.foo.bar && appData.foo.bar.setting;
Another option:
try {
var myVal = appData.foo.bar.setting;
} catch (e) {
var myVal = undefined;
}
The . operator is not really intended for accessing objects like this. Probably using a function would be a good idea.
The optional chaining operator (?.) was introduced in ES2020. Now, you should be able to write:
const myVal = appData?.foo?.bar?.setting
I find other approaches a bit immense. So, what would be the major drawback of the following approach:
// Pass the path as a string, parse it, and try to traverse the chain.
Object.prototype.pathExists = function(path) {
var members = path.split(".");
var currentMember = this;
for (var i = 0; i < members.length; i++) {
// Here we need to take special care of possible method
// calls and arrays, but I am too lazy to write it down.
if (currentMember.hasOwnProperty(members[i])) {
currentMember = currentMember[members[i]];
} else {
return false;
}
}
return true;
}
Basically, we define a method on the object (not necessarily) and that method takes the path to a nested object and returns existence confirmation, likeappData.pathExists("foo.bar.setting");
EDIT:
Check object[prop] == undefined is not semantically correct since it will return false even if the property is defined although its value is undefined; that is why I use hasOwnProperty to check is the property defined. This might not be important if one needs to just fetch the value.
If, after:
var myVal = appData.foo && appData.foo.bar && appData.foo.bar.setting;
myVal is not undefined, it will hold the value of appData.foo.bar.setting.
You can try this
var x = {y:{z:{a:'b'}}}
x && x.y && x.y.z && x.y.z.a //returns 'b'
This is not as good as the groovy expression but it works. The evaluation stops after encountering the first undefined variable.
var product = ...,
offering = (product||{}).offering,
merchant = (offering||{}).merchant,
merchantName = (merchant||{}).name;
if (merchantName)
displayMerchantName(merchantName);
http://osteele.com/archives/2007/12/cheap-monads
I just cooked this up so it might not work exactly right, I've also included two test cases.
function hasPropertyChain(o, properties) {
var i = 0,
currentPropertyChain = o;
if(!o) {
return false;
}
while(currentPropertyChain = currentPropertyChain[properties[i++]]);
return i - 1 === properties.length;
}
alert(hasPropertyChain({a:{b:{c:'a'}}}, ['a','b','c'])); // true
alert(hasPropertyChain({a:{b:{c:'a'}}}, ['a','b','c', 'd'])); // false

Object (string or array) NAME. how to get it?

I need a prototype done in this way:
Array.prototype.getname=function(){ [...]return arrayname; }
So I can:
z=new Array;
alert(z.name);
and I should have "z" in the alert.
I'm working on Chrome and caller/callee seem to return empty.
The best you can do is to always explicitly set the array's name when you create it:
var z = [];
z.name = 'z';
You could do this by having a function makeArray that sets the name passed as an argument:
function makeArray(name) {
var arr = [];
arr.name = name;
return arr;
}
The essential problem is that the several variables can point to the same array:
var z = [],
x = z;
Then what should the name be: z or x?
The problem is that a variable (like an array) can have several names. For example:
var a = new Array();
var b = a;
a[0] = "hello";
alert(b[0]);//"hello"
What is the name of the array, a or b?
Can't be done. There is no way to access the name of the variable which is storing a reference to the object. Perhaps you should explain why you need behavior like this, so someone can suggest you an alternative way to approach the problem.
The only way to do this would be to brute-force check all properties of the global object (assuming the variable is global) until you find a property that === the array. Of course, it could be referenced by multiple variables so you would have to pick one of the names you get. This implementation gets the first variable to reference the array and will work in browsers and web worker threads:
Array.prototype.getName = function () {
var prop;
for (prop in self) {
if (Object.prototype.hasOwnProperty.call(self, prop) && self[prop] === this) {
return prop;
}
}
return ""; // no name found
};
Of course, I don't recommend this at all. Do not do this.
Further testing the object.getName().. i found this 'problem':
test1='test'
test
test2='test'
test
test1.getName()
test1
test2.getName()
test1
this happens because they have the same content and getName checks for content.
a solution could be to return an Array in that case.
But I'm still searching for a definitive solution to this brainteasing problem.
So For now the best answer is Elijah's
More generally:
Object.prototype.getName = function () {
var prop;
for (prop in self) {
if (Object.prototype.hasOwnProperty.call(self, prop) && self[prop] === this && self[prop].constructor == this.constructor) {
return prop;
}
}
return ""; // no name found
};
I wonder if there are better solutions.

Categories

Resources