访问nodejs上的function.caller

我有一个任务取决于function.caller健全性检查一个调用者被授权。

根据这个url,所有主stream浏览器都支持调用者…所有的unit testing都通过了:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

但是,nodejs拒绝所有访问function.caller的尝试(将其报告为空)。

我打开的build议,使这个工作nodejs …我讨厌这个框架只适用于浏览器。

谢谢!

Caller-id npm软件包使得它像馅饼一样简单: https : //www.npmjs.com/package/caller-id从文档:

 var callerId = require('caller-id'); // 1. Function calling another function function foo() { bar(); } function bar() { var caller = callerId.getData(); /* caller = { typeName: 'Object', functionName: 'foo', filePath: '/path/of/this/file.js', lineNumber: 5, topLevelFlag: true, nativeFlag: false, evalFlag: false } */ } 

您可以使用arguments.callee.caller来获取对调用者的引用。 不过,我认为(仍然)不推荐使用(尽pipe最终的移除可能会导致某些情况下出现问题,请参阅此处的讨论),也错过了一些编译器/解释器优化。

例:

 function foo() { bar(); } function bar() { console.log(arguments.callee.caller.name); } foo(); // outputs: foo 

因为function.caller能在nodejs中工作,但在与Object.defineProperty getter / setter结合时失败,所以我会考虑这个在nodejs中的错误,而不是由nodejsselect不支持function.caller。

我对这个派对比较迟,但是我也试图使用arguments.caller,经过大量的试验和错误之后,如果你使用prototype,这是可能的。

这不起作用:

 class MyClass { watchProperties() { Object.defineProperty(this, 'myproperty', { get: function f(value) { }, set: function f(value) { console.log(arguments.caller.name); } }); } } var foo = new MyClass; foo.watchProperties(); foo.myproperty = 'bar'; 

但是通过使用原型,它可以:

class MyClass {

}

 MyClass.prototype.watchProperties = function() { Object.defineProperty(this, 'myproperty', { get: function f(value) { }, set: function f(value) { console.log(arguments.caller.name); } }); }; var foo = new MyClass; foo.watchProperties(); foo.myproperty = 'bar'; 

这在function上是相同的。 我不知道为什么一个是由节点阻止,另一个不是,但这是在节点6.0中的一个工作解决方法。