在javascript中为变量赋值函数

时间:2014-12-12 09:00:54

标签: javascript

我希望myAlert变量中的整个函数。 我能够实现它,但是有一个问题 预期的输出是

function () {P}

但我正在

function () {_DateControlId}

注意:我不希望将函数表达式转换为字符串以实现结果。

See this fiddle

1 个答案:

答案 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());