Access function.caller function on nodejs

I have a task dependent on the function.caller function to check the caller is up and running.

According to this url, the caller is supported in all major browsers ... and all my unit tests pass:

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

However, nodejs rejects all attempts to access the .caller function (reports this as null).

I am open to suggestions that this work works on nodejs ... I would not want this environment to work only in browsers.

Thanks!

+5
source share
4 answers

The npm package for caller-id makes this as easy as pie: https://www.npmjs.com/package/caller-id from the docs:

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 } */ } 
+7
source

Because function.caller DOES works in nodejs, but it fails when combined with get.defineProperty getters / seters, I'm going to consider this a mistake in nodejs, and not choosing nodejs not to support the function. caller.

0
source

I'm late for this party, but I also tried to use arguments.caller after a lot of trial and error, perhaps if you use a prototype.

This does not work:

 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'; 

But using the prototype, he does the following:

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'; 

It is functionally identical. I don’t know why one of them is prevented by node and the other is not, but this is a workaround in node 6.0.

0
source

You can use arguments.callee.caller to get a link to the caller. However, I believe that it is (still) outdated (although its possible removal may cause a problem for some cases, see here for this discussion), and you will skip on some compiler / interpreter optimizations.

Example:

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

Source: https://habr.com/ru/post/1202304/


All Articles