javascript - 我试图将我的函数调用存储在一个对象中

标签 javascript html function object properties

我试图将函数调用存储在对象中,因此当我引用该属性时,它会运行该函数。这是我写的代码,但它不起作用。这是我到目前为止的代码。 html:

<!DOCTYPE html> 
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tetris(test)</title> 
    <link rel="stylesheet" href="styleSheets/main.css">
    <script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
    <script src = "js/jquery.1.js"></script>
    <script src = "js/main.js"></script>
  </head>
  <body>
      <svg id="container" width= "500" height= "650" style= "background-color: black" position= "relative">
      </svg>

  </body>
</html>

JS:

var svgNS = "http://www.w3.org/2000/svg";
var htmlNS = "http://www.w3.org/1999/xhtml";

function createShape1() {
    var elem = document.getElementById("container");
    var shape = document.createElementNS(svgNS, "rect");
        shape.id = "shape1";
        shape.style.width = "150px";
        shape.style.height = "50px";
        shape.style.fill = "orange";
        shape.style.y = "50px";
        shape.style.x = "150px"
        shape.style.position = "absolute"
        elem.append(shape);
    var shape2 = document.createElementNS(svgNS, "rect");
        shape2.id = "shape2";
        shape2.style.fill = "orange";
        shape2.style.x = "200px";
        shape2.style.width = "50px";
        shape2.style.height  = "51px";
        elem.append(shape2);
};
window.onload = randShape;
function createShape2() {
    var elem = document.getElementById("container");
    var shape = document.createElementNS(svgNS, "rect");
    shape.id = "shape1";
        shape.style.width = "100px";
        shape.style.height = "100px";
        shape.style.fill = "red";
        shape.style.x = "200px"
        shape.style.position = "absolute"
        elem.append(shape);
};
var shapes = {
    "shape1": createShape1(),
    "shape2": createShape2()
};
function randShape() {
    var x = Math.floor(Math.random() * 2);
    shapes.x;
}

因此,如果您有任何建议让我的代码生成形状的随机属性,每个属性都应该生成自己的形状。

最佳答案

问题是如何访问该值并在访问您要调用的函数之前进行函数调用

var shapes = {
  "shape1": createShape1,
  "shape2": createShape2
};

function randShape() {
    var x = Math.floor(Math.random() * 2) + 1;
    (shapes["shape" + x]).call(shapes);
}

关于javascript - 我试图将我的函数调用存储在一个对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59316638/

相关文章:

c - 使用 main(int argc,char **argv) {} 作为函数重写程序

string - 使用扩展功能将String中的每个单词大写

javascript - 用新的 HTML 内容替换每个出现的单词

javascript - 以时间格式制作 highcharts 的 y 轴 hh :mm

javascript - jQuery 并选择下一个列表项对象

html - 照片漂浮在页面元素上?

html - Twitter Bootstrap 网格和 _slightly_ 不均匀的单元格高度

javascript - script-src 包含无效源 : '' wasm-eval' while using web worker

php - Wordpress 在选择自定义字段时应用特定的 css

c - 当函数的返回类型不允许我这样做时,如何在 C 中返回错误代码?