我想调用实例方法,其名称与func输入元素一起传递,但代码失败,因为它在全局window中找不到TestClass个实例方法.我如何才能做到这一点?

class TestClass {
  func = document.getElementById('func');

  result = document.getElementById('result');

  func1 = () => {
    this.result.innerHTML = 'func1 called';
  };

  func2() {
    this.result.innerHTML = 'func2 called';
  }

  funcListener = () => {
    window[this.func.value]();
  };

  constructor() {
    this.func.addEventListener('change', this.funcListener);
  }
}

new TestClass();
functest.html

<!doctype html>
<html lang="en-US">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>functest</title>
</head>

<body>
  <input id="func" placeholder="enter function to call: func1, func2" type="text" maxlength="200">
  <label id="result" for="func">result</label>
</body>

推荐答案

window[this.func.value]()—你的函数被包装在类中,而不是全局函数,所以使用this[this.func.value]()代替.

class TestClass {
  func = document.getElementById('func');

  result = document.getElementById('result');

  func1 = () => {
    this.result.innerHTML = 'func1 called';
  };

  func2() {
    this.result.innerHTML = 'func2 called';
  }

  funcListener = () => {
    this[this.func.value]();
  };

  constructor() {
    this.func.addEventListener('change', this.funcListener);
  }
}

new TestClass();
functest.html

<!doctype html>
<html lang="en-US">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>functest</title>
</head>

<body>
  <input id="func" placeholder="enter function to call: func1, func2" type="text" maxlength="200">
  <label id="result" for="func">result</label>
</body>

Javascript相关问答推荐

Bootstrap动态选项卡在切换选项卡后保持活动状态,导致元素堆叠

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

Chart.js V4切换图表中的每个条,同时每个条下有不同的标签.怎么做?

在Three JS中看不到补间不透明度更改效果

我可以使用空手道用户界面来获取网页的当前滚动位置吗?

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

将Node.js包发布到GitHub包-错误ENEEDAUTH

将数组扩展到对象中

未捕获语法错误:Hello World中的令牌无效或意外

判断函数参数的类型

Pevent触发material 用户界面数据网格中的自动保存

JavaScript -复制到剪贴板在Windows计算机上无效

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

在Press Reaction本机和EXPO av上播放单个文件

是否有静态版本的`instanceof`?

如何在Firebase中读取对象的特定字段?

MAT-TREE更多文本边框对齐问题

使用Java脚本筛选数组中最接近值最小的所有项

从客户端更新MongoDB数据库

CSS网格使页面自动滚动