https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240917/f6a4bc9ab69d9a8ac90d243d80b32f7a.png https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240917/3d755fe4783c223f81a57de9f5723907.png 为何第一种无法输出内容呢,但是第二种可以。这个闭包操作学的很蒙 希望可以被解决,在下为新手,谢谢
问题来自于"codewars The builder of things" (https://link.segmentfault.com/?enc=nc5rvEW%2FVPC95ltC06Zu6A%3D%3D.ET9zgztamRR4vYb51nQUTNP%2BfdbaJenm9axMcllAFB%2FlVWBApAPA6Qay%2B7S7R4tZUGv%2B8ren%2FKrCKOtguYWl985NIo%2BpZMkiXeErO5Pav7U%3D) 要求我们实现一个Thing类,其中一点要求如下所示: describe('#can', function(){ describe('jane.can.speak(phrase => `${name} says: ${phrase}!`)', function(){ it('should create a speak method on jane', function(){ const jane = new Thing('Jane'); jane.can.speak(phrase => `${name} says: ${phrase}!`); expect(jane.speak('hello')).to.equal('Jane says: hello!'); }); }); 难点是这里的"name"的值从哪里找啊? 我想到的一个方案是使用"with",但是codewars上使用的是严格模式,不能使用"with"。 class Thing { // TODO: Make the magic happen /* const jane = new Thing('jane'); console.log(jane.name) => 'jane' */ constructor(name) { this.name = name; /* can jane.can.speak(phrase => `${name} says: ${phrase}!`) jane.speak('Hello') => 'jane says: Hello!' where to find name ? => this */ this.can = { speak: (callback) => { this.speak = (...args) => { let res; with(this) { res = callback(...args); }; return res; } } } }