推荐 最新
强哥喝假酒

如何使用 javascript 元编程实现 Thing 类?

问题来自于"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; } } } }

0
1
0
浏览量111