首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正弦间谍构造方法

正弦间谍构造方法
EN

Stack Overflow用户
提问于 2017-09-24 20:53:15
回答 1查看 1.3K关注 0票数 1

我发现了几个相关的问题,但似乎都没有帮助我实现什么。

因此,我想窥探构造函数方法,以便当使用构造函数创建的对象在中调用此方法时--另一个函数--,我可以知道调用的参数。

示例:

代码语言:javascript
复制
function Constructor(args){
  this.method = sinon.spy()
}

function someFunction(){
  obj = new Constructor(args);
  obj.method()
}

console.log(Constructor.method.args[0]); // list the args of the obj.method() call

任何帮助都将不胜感激。

编辑:我意识到我把问题说错了,最后问了一些非常琐碎的问题:-)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-24 21:08:28

这样,您就可以监视Constructor.method:

代码语言:javascript
复制
function Constructor(args){
    this.method = function() {}
}

const obj = new Constructor();
obj.method = sinon.spy(obj.method);
obj.method('someArg');

console.log(obj.method.args[0]);  // [ 'someArg' ] 

但是,正如您所说的那样,您不可能有一个静态方法和一个同名的类方法,如果您实例化该类不止一次,那又如何呢?无论如何,我能提供的最好的解决方案是在构造函数上使用代理,如下所示:

代码语言:javascript
复制
function Constructor(args) {
    this.method = function () {}
}

const ProxyConstructor = new Proxy(Constructor, {
    construct: function (target, args, newTarget) {
        const c = new target(...args);
        const origMethod = c.method;
        c.method = function (...args) {
            ProxyConstructor.methodArgs = ProxyConstructor.methodArgs || [];
            ProxyConstructor.methodArgs = ProxyConstructor.methodArgs.concat(args)
            origMethod(...args);
        };
        return c;
    }
});


function someFunction() {
    obj = new ProxyConstructor();
    obj.method('test')
}

someFunction();
console.log(ProxyConstructor.methodArgs); // ['test']

您可以将该代码粘贴到文件中并进行尝试。另外,在编写测试时,您可能需要重构代码以使其可测试,或者在编写代码(TDD)之前先编写测试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46394740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档