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://www.sitepoint.com/call-javascript-function-string-without-using-eval/
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16451166.html
未经授权禁止转载,违者必究!