xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js function name string to function All In One

js function name string to function All In One

namespace ✅

window[namespace]['callback']();

eval 👎

eval()

demo

bug

  render() {
    // console.log('this.type =', this.type);
    this.btn.className = `wcui-button ${this.types[this.type]}`;
    console.log('this.callback', this.callback)
    if(this.callback) {
      this.btn.addEventListener('click', () => {
        // js function name string to function ???
        callback(this.type);
        // window.callback(this.type);
        // window[this.namespace].callback(this.type);
      });
    } else {
      console.log('❌ no callback passed');
    }
  }

solution

const callback = (type = '') => {
  console.log('button type', type);
  alert(`🎉 button type =${type}`);
}

// 挂载到 window 上
window.callback = callback;

// window.wcui.button.callback = callback;

  render() {
    // console.log('this.type =', this.type);
    this.btn.className = `wcui-button ${this.types[this.type]}`;
    console.log('this.callback =', this.callback, window[`${this.callback}`])
    if(this.callback) {
      this.btn.addEventListener('click', () => {
        // js function name string to function ❌
        // this.callback(this.type);
        window[`${this.callback}`](this.type);
      });
    } else {
      console.log('❌ no callback passed');
    }
  }

refs

https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string

https://www.sitepoint.com/call-javascript-function-string-without-using-eval/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-07-06 15:56  xgqfrms  阅读(34)  评论(1编辑  收藏  举报