使用 javascript 元编程实现 thing 类
问题:
实现一个 thing 类,该类的 can 方法可以动态创建新方法,如以下示例代码所示:
const jane = new thing('jane'); jane.can.speak(phrase => `${name} says: ${phrase}!`); expect(jane.speak('hello')).to.equal('jane says: hello!');
问题所在:
立即学习“Java免费学习笔记(深入)”;
在 can.speak 中,name 变量的值从哪里获取?
解决方案:
class Thing { constructor(name) { this.name = name; globalThis.name = name; } }
以上就是如何使用 JavaScript 元编程实现 Thing 类中的 can 方法动态创建新方法?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号