简体   繁体   English

是否可以在函数内部获取结果变量名称?

[英]Is it possible to get result variable name inside function?

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() ). 我想获取变量名称(示例中的user_name1user_name2 ),该变量名称是此函数( GetUserName() )内部函数( 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM