Is it possible to get result variable name inside function? - javascript

I want to get variable name(user_name1 or user_name2 from sample) which is get result of a function(GetUserName()) inside this function(GetUserName()). I need this name for create object with the same name on server side(data synchronization).
function GetUserName(){
let result_variable_name = ????; //in (1) result_variable_name == 'user_name1', in (2) result_variable_name == 'user_name2'
socket.send("object_name", result_variable_name);
return "Some user name";
}
let user_name1 = GetUserName(); //(1)
let user_name2 = GetUserName(); //(2)
Is it possible? How?

No. Just no. Variable names should have no intrinsic meaning. They're just placeholders in an algorithm, and sometimes you can't even control their names to the extend you need. Also, the variable doesn't really exist yet at the time you call the function. And even if it did, there's no sane way to figure out what variable the result of the function will be assigned to from within said function.
Also:
let users = [GetUserName(), GetUserName()];
Now what?
Pass the name explicitly into the function, period.
GetUserName('user_name1')

Related

Sequelize.fn : Constructing the update argument outside the call

Issue Description
I'm currently trying to make updates on passwords using sequelize.fn.
I've seen numerous sites, including the Sequelize's manual, yet I found too few articles that approaches my case, and none of them seems to solve it.
Moreover, the function to encrypt the passwords need nested function, so I need to gradually construct the nested function
by putting the successive arguments into variables.
I have not found anything on constructing the functions, thus using sequelize.fn outside the arguments of the functions find and updates.
Additional context
In my case, " crypt('password', gen_salt('bf', 4)) " (in Postgres) needs to become
sequelize.fn('crypt', 'password', sequelize.fn('gen_salt', 'bf', 4)) and to be stored into a variable
When I inject it into the update function, an Fn Object is injected, and the result in the database seems to be a memory address instead of the result of the crypt function.
I may post a code example so you can have a better understanding of what I'm trying to do and I think should be added into the documentation
I did not made this doc issue to resolve my issue, only to point out what I think is lacking in the documentation
I will ask StackOverflow for help regarding my issue.
//Take a format and a value, and applies the functions inside the format onto the value
function recursSequelizeFn (format, value) {
const sequelize = db.sequelize;
let nextId = 0;
let matches;
let finalArgs = {};
//The RegEx finds the function calls of which parameters aren't functions themselves
//As the format string is modified on each loop, I need to initialize the RegEx on each loop
while ((matches = (/(\w+)\(([^(,)]+)?(?:,([^(,)]+))*\)/g).exec(format)) !== null) {
//matches[0] is the whole expression
//matches[1] is the function's name
//matches[>=2] are the arguments
let func = matches[1];
let args = matches.slice(2);
for (let argNo in args) {
//Transforms DB's columns into Sequelize-interpreted columns
//I do not check the column that is found, because I do not have others columns than the one that is being treated
args[argNo] = args[argNo].replace(/seqCol_(\w+)/g, (correspondance, p1, decalage, chaine)=>{return value;});
//If the parameter was previously saved, we replace its reference by its value
args[argNo] = args[argNo].replace(/(#\d+)/g, (correspondance, p1, decalage, chaine)=>{return finalArgs[p1];});
}
//finally, we save the value of the function and replace the whole expression by a reference
finalArgs['#'+nextId]=sequelize.fn(func, ...args);
format = format.replace(matches[0], '#'+nextId);
nextId++;
}
//When the treatment is finished, we return the last value saved into the array
//Or we return the original value if we have not made any change (the array will be empty)
return finalArgs['#'+(nextId-1)]||value;
}
Object.keys(req.message.attributes).map((key)=>{
//req.message.attributes[key] contains the formatting needed to be put onto the value
//e.g. crypt(password, gen_salt('bf', 4))
//req.body[key] contains the value
//e.g. '1234'
let seqValue = util.recursSequelizeFn(req.message.attributes[key], req.body[key]);
req.body[key] = seqValue;
});
//mainModel is a sequelize model
mainModel.update(req.body, {where: {id:req.params.id}, logging:console.log})
.then() //...

How know variable name in javascript?

Suposse an function:
function get(){}
this will get an variable
var name = "Eduardo";
get(name);
function get(n) {}
And i want to show the name of the variable that was passed, without know this name.
function get(n) {
return getNameVariableFromValue(n); // Pseudocode for explain my question
}
so, i want the name of variable without previouslu knowing this name.
PD: My question is mainly to know, who is a variable in the window object, without know this name or value
Your question assumes that no two properties would ever have the same value, which is highly unlikely. But, making that wild assumption, you'd need to make the new window property explicitly rather than just declare a global variable and then you could use Object.keys() to enumerate all the key names of the window object, looking for the one that matches your value. When found, report the key name.
window.myGlobal = "Test";
Object.keys(window).forEach(function(key){
if(window[key] === "Test"){
console.log(key);
}
});
This code won't work in the Stack Overflow snippet environment due to sandboxing, but you can see it working here (make sure to have your developer's tools console open when running).
You can send the value as an object to the function and do something like below
function get(n) {
return Object.keys(n)[0];
}
var name ="Test1";
var name2 = "Test2"
console.log(get({name}))
console.log(get({name2}))

Put a variable between double quotes

I have a small question:
I have a function in javascript.
var func = function(variable)
{
result = variable;
}
If I call
func(rabbit);
I need the result to be "rabbit".
I cannot figure out how to put the variable between the two quotes.
Assuming rabbit is supposed to be a string:
func("rabbit");
If rabbit is actually a variable, then there's no way to do this because the variable (meaning the implementation's representation of a variable) isn't actually passed to the function, but rather its value is.
Actually there's an ancient way to retrieve the variable name.
var func = function(variable)
{
console.log(variable); // outputs "white"
console.log(arguments.callee.caller.toString().match(/func\((.*?)\)/)[1]); // outputs "rabbit"
}
rabbit = 'white';
func(rabbit);
See it running http://jsfiddle.net/Q55Rb/
You could do this
function whatever(input) {
return '\"' + input + '\"';
}
result should be in quotes
I could not tell from your question whether you wanted "rabbit" to be the property name, or the value. So here is both:
var func = function(variable) {
window[variable] = 'abc'; // Setting the variable as what is passed in
window.result = variable; // Normal
}
func('rabbit'); // Will set both window.rabbit to 'abc', and window.result to 'rabbit'
I wouldn't advise setting global variables, though. More info
Ok I thought that was my problem. Now I'm pretty sure that's not it but I have no clue what it is then.
I have this in my function:
defaults = {title :{'pan':-1,'left':0,'volume':0.30,'top':111}};
Where title is a variable from the function. But as a result I get title in defaults instead of the actual title stored in the variable named title. Do you understand me?

Remembering the last value passed to a JavaScript function called on click

Below is my code fragment:
<div onclick = "myClick('value 1')">
button 1
</div>
<div onclick = "myClick('value 2')">
button 2
</div>
Basically when I for each click on a different div, a different value will be passed to the JavaScript function.
My Question is how can I keep track of the value passed in the previous click?
For example, I click "button 1", and "value 1" will be passed to the function. Later, I click on "button 2", I want to be able to know whether I have clicked "button 1" before and get "value 1".
Just add it to a variable in your script:
var lastClicked;
var myClick = function(value) {
lastClicked = value;
};
You can define somekind of variable, like var lastUsed;
add additional line to your function:
var lastUsed = null;
function myClick(value){
prevClicked = lastUsed; //get the last saved value
...
lastUsed = value; //update the saved value to the new value
...
}
And here you go
You need a variable. Variables are like little boxes in which you can store values. In this case, we can store the value that was last passed to the function myClick.
In Javascript, you can define a variable like this:
var lastClickedValue;
You can "put" a value into that variable. Let's say you want to put your name in there. You would do this:
lastClickedValue = 'sams5817';
Now here's the tricky bit. Variables have "scope". You might want to think about it as their "life-time". When a variable reaches the end of its scope, you cannot read or write to it anymore. It's as if it's never been. Functions define a scope. So any variable you define in a function will disappear at the end of the function. For example:
function myClick(value)
{
var lastClickedValue;
alert('lastClickedValue is = ' + value);
lastClickedValue = value;
}
That looks almost right, doesn't it? We declared a variable, display its last value, and update it with the new value.
However, since the lastClickedValue was declared in the function myClick, once we've reached the end of that function, it's gone. So the next time we call myClick, lastClickedValue will be create all over again. It will be empty. We call that an "uninitialized" variable.
So what's the problem? We're trying to remember a value even after the end of myClick. But we declared lastClickedValue inside myClick, so it stops existing at the end of myClick.
The solution is to make sure that lastClickedValue continues to exist after myClick is done.
So we must delcare lastClickedValue in a different scope. Luckily, there's a larger scope called the "global scope". It exists from the moment your page loads, and until the user moves on to another webpage. So let's do it this way:
var lastClickedValue;
function myClick(value)
{
alert('lastClickedValue is = ' + value);
lastClickedValue = value;
}
It's a very small difference. We moved the declaration of the variable lastClickedValue to be outside the function myClick. Since it's outside, it will keep existing after myClick is done. Which means that each time we call myClick, then lastClickedValue will still be there.
This will let you know what the last value passed to myClick was.
Finally, I'd like to advise you to look for some kind of Javascript tutorials. I wish I knew of some good ones to recommend, but I'm certain you can find a few on the Internet. If you try to write programs before understanding what you're doing, you'll find yourself producing work that is less than what you're capable of. Good luck!
I suppose you need something like this
var clickedButtons = [];
function myClick(value){
...
clickedButtons.push(value);
...
}
I am surprised that no one else mentioned this, but since functions are first class objects in JavaScript, you can also assign attributes and methods to functions. So in order to remember a value between function calls you can do something like I have with this function here:
function toggleHelpDialog() {
if (typeof toggleHelpDialog.status === 'undefined')
toggleHelpDialog.status = true;
else
toggleHelpDialog.status = !toggleHelpDialog.status;
var layer = this.getLayer();
if (toggleHelpDialog.status) layer.add(helpDialog);
else helpDialog.remove();
layer.draw();
}
Here I have added an attribute named 'status' to the toggleHelpDialog function. This value is associated with the function itself and has the same scope as the toggleHelpDialog function. Values stored in the status attribute will persist over multiple calls to the function. Careful though, as it can be accessed by other code and inadvertently changed.
we can leverage javascript static variables
One interesting aspect of the nature of functions as objects is that you can create static
variables. A static variable is a variable in a function‘s local scope whose value persists across
function invocations. Creating a static variable in JavaScript is achieved by adding an instance
property to the function in question. For example, consider the code here that defines a function
doSum that adds two numbers and keeps a running sum:
function doSum(x,y){
if (typeof doSum.static==='undefined'){
doSum.static = x+y;
}else{
doSum.static += x+y;
}
if (doSum.static >= 100){doSum.static = 0;doSum.static += x+y;}
return doSum.static;
}
alert(doSum(5,15))
alert(doSum(10,10))
alert(doSum(10,30))
alert(doSum(20,30))

Executing a function by name, passing an object as a parameter

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );

Categories