javascript - 使用 myFuncArray.shift()() 调用函数

标签 javascript

我在使用 shift() 调用我放入数组中的函数时遇到问题。我整理了一个简单的例子来说明这个问题。

本质上,该函数被调用,但是,对函数中变量的更改不会保留。

<html>
<head>
<script type="text/javascript">
Taco = function() {};
Taco.prototype.init = function() {
  this.ex1 = "ex1 in init()";
  alert(this.ex1);
};
</script>
</head>
<body>
<input type="Submit" onClick="withShift();" value="withShift"/>
<div id="div1">
</div>
<input type="Submit" onClick="noShift();" value="noShift"/>
<div id="div2">
</div>
<script type="text/javascript">
// This calls init but does not hold the value of ex1 after the call
withShift = function() {
taco = new Taco();
  funcQ = [];
  funcQ.push(taco.init);
  funcQ.shift()(); 

  div1 = document.getElementById("div1")
  div1.appendChild(document.createTextNode(taco.ex1));
};

// this calls init and it holds the value...
noShift = function() {
  taco2 = new Taco();
  taco2.init();
  div1 = document.getElementById("div2")
  div1.appendChild(document.createTextNode(taco2.ex1));
}
</script>
</body>
</html>

预先感谢您的任何建议。

最佳答案

当您传递方法指针时,JavaScript 不会记住 this 参数。您必须在函数对象上使用 callapply 方法来显式传递 this

在传递函数指针时,使用 taco.init 与使用 Taco.prototype.init 大致相同。工作方式如下:

taco = new Taco();
funcQ = [];
funcQ.push(taco.init);
// pass taco first, and the non-hidden function arguments after;
// in this case, no other argument
funcQ.shift().call(taco);

如果你不能使用这种语法,你可以使用匿名函数:

taco = new Taco();
funcQ = [];
funcQ.push(function() { taco.init(); });
funcQ.shift()();

与不携带 this 参数的 object.method 语法相反,闭包是可靠的。

关于javascript - 使用 myFuncArray.shift()() 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3681341/

相关文章:

javascript - Protractor - 等待多个元素

javascript - jquery、javascript 中的后台线程

javascript - paypal结账按钮在javascript中获取json响应

javascript - onclick打开窗口和具体大小

javascript - Node : How to prepare code for production environment

javascript - ExtJS 从 URL 获取更新进度条

javascript - 将多个选中的复选框标签放入数组中

javascript - 如何测试 AngularJS $asyncValidators 包括 $http 调用

php - 如何限制fancyupload中的多个文件选择?

javascript - 从数组中随机选择一个元素,重复直到满足条件