使变量字符串成为函数名称

时间:2017-05-27 22:49:38

标签: javascript html canvas

我想知道是否有办法让var值成为一个函数。我目前正在开发一个制作脚本并运行代码的项目,但是当所有的函数名相同而不是运行独立代码的两个脚本时,他们会一致地编写相同的代码。如果你能告诉我如何做到这一点,那将是一个巨大的帮助!但我不确定它是否可行。没有一些代码



var update = setInterval(function(){
  checkDotPop();
  sc();
}, 1);

var canvas = document.getElementById("canvas");
var body = document.getElementById("body");

totalDots = 2;
aliveDots = 1;
//styling
body.style.border = "0px";
canvas.style.backgroundColor = "black";

function checkDotPop(){
  while(aliveDots != totalDots){
    makeDot();
    aliveDots++;
  }
}
function makeDot(){
  var scr = document.createElement("script");
  scr.setAttribute("id", "dot" + totalDots);
  document.body.appendChild(scr);
  var script = document.getElementById("dot" + totalDots);
  script.innerHTML = "var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var rand1; var rand2; function changeRand(){rand1 = Math.floor(Math.random() * 300) + 1; rand2 = Math.floor(Math.random() * 300) + 1;} function sc(){ changeRand(); context.fillStyle = 'red'; context.fillRect(rand1, rand2, 10, 10); context.fill();";
}

<!DOCTYPE html>
<html>
<head>
</head>
<body id="body">
<canvas id="canvas" height="500px" width="500px"/>
</body>
</html>
&#13;
&#13;
&#13;

它会说&#34; sc未定义&#34;但在我的版本中(使用记事本)sc是一个gobal函数,可以从脚本调用到脚本

1 个答案:

答案 0 :(得分:0)

您缺少sc功能的结束括号。

var update = setInterval(function(){
  checkDotPop();
  sc();
}, 1);

var canvas = document.getElementById("canvas");
var body = document.getElementById("body");

totalDots = 2;
aliveDots = 1;
//styling
body.style.border = "0px";
canvas.style.backgroundColor = "black";

function checkDotPop(){
  while(aliveDots != totalDots){
    makeDot();
    aliveDots++;
  }
}
function makeDot(){
  var scr = document.createElement("script");
  scr.setAttribute("id", "dot" + totalDots);
  document.body.appendChild(scr);
  var script = document.getElementById("dot" + totalDots);
  script.innerHTML = "var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var rand1; var rand2; function changeRand(){rand1 = Math.floor(Math.random() * 300) + 1; rand2 = Math.floor(Math.random() * 300) + 1;} function sc(){ changeRand(); context.fillStyle = 'red'; context.fillRect(rand1, rand2, 10, 10); context.fill();}";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body id="body">
<canvas id="canvas" height="500px" width="500px"/>
</body>
</html>