我希望myAlert
变量中的整个函数。
我能够实现它,但是有一个问题
预期的输出是
function () {P}
但我正在
function () {_DateControlId}
注意:我不希望将函数表达式转换为字符串以实现结果。
答案 0 :(得分:2)
尝试返回变量并将其作为警告myAlert()
中的函数调用:
var _DateControlId = "P";
var myAlert = function() {
return _DateControlId;
};
alert(myAlert());

澄清js解析器:
[step 0]
// All variables is assigned it's value.
// So _DateControlId now is same as string "P"
var _DateControlId = "P";
var myAlert = function() {
return _DateControlId;
};
alert(myAlert());
[step 1]
// All variables are replaced with it's values.
// So _DateControlId is replaced with string "P" (as it's his value)
var myAlert = function() {
return "P";
};
alert(myAlert());
[step 2]
// Functions are evaluated. So your anonymous function is evaluated value of _DateControlId.
var myAlert = "P";
alert(myAlert());
[step 3]
// variable are placed in alert function call. Alert function accepts only string parameters
alert("P");
[第4步] //警报功能被执行,你会弹出一个表示" P" - myAlert函数的值 //反过来又是_DateControlId的值。
现在您想要在弹出消息中看到function () {P}
,您需要将其传递给字符串
所以基本上你的代码最终必须如下:
var _DateControlId = "P";
var myAlert = function() {
return "function () {" + _DateControlId + "}";
}
alert(myAlert());