Javascript show all functions

List of global user defined functions in JavaScript?

Is it possible to get a list of the user defined functions in JavaScript? I’m currently using this, but it returns functions which aren’t user defined:

var functionNames = []; for (var f in window) < if (window.hasOwnProperty(f) && typeof window[f] === 'function') < functionNames.push(f); >> 

In Firefox this gave the expected results, namely all the functions on the global object, window. What false positives are you referring to?

I’m also wondering what false positives you are talking about? I also noticed that you haven’t declared f, so it will end up in the global scope if it was part of an function.

3 Answers 3

I’m assuming you want to filter out native functions. In Firefox, Function.toString() returns the function body, which for native functions, will be in the form:

function addEventListener()

You could match the pattern /\[native code\]/ in your loop and omit the functions that match.

As Chetan Sastry suggested in his answer, you can check for the existance of [native code] inside the stringified function:

Object.keys(window).filter(function(x) < if (!(window[x] instanceof Function)) return false; return !/\[native code\]/.test(window[x].toString()) ? true : false; >); 
Object.keys(window).filter(function(x) < return window[x] instanceof Function && !/\[native code\]/.test(window[x].toString()); >); 

in chrome you can get all non-native variables and functions by:

Источник

How to view all JavaScript functions called in real time?

I want to figure out how a website reloads it’s content using AJAX. Therefore i would like to see what JS functions are called in real time because I can’t figure out what function is responsible for reloading the page dynamically. How to see all executed functions JS in real time in FF, Chrome, Opera or IE?

I have firebug. I can’t put break point because i don’t know what function it is. Have you red my question? Please do it. I need something to see what functions are called not to put break point into a function.

If that page has jQuery, refer to this answer to see what functions are wired up to the elemnet causing an ajax call, then, you can use breakpoints and step function to trace it.

6 Answers 6

Maybe using the ‘profile’ button in the firebug console tab can give you an indication of the function(s) that are fired. Furthermore you can tell firebug’s console to show xmlhttp requests (expand ‘console’ at the top of the firebug screen. After that, If an ajax request fires, it should be visible in the console. In the ‘post’ tab in such a request you may be able to infer the function triggering the request, looking at the parameters.

I’m trying to debug an issue only in IE some sort of infinite loop, but If I have to use Firefox to get a list of methods being called so I at least know where to look that’s cool. but when I use the profile button and then load the page, the profiling resets when the new page loads. So how to catch what is run when the page first loads?

Источник

How to display all methods of an object?

You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not. For example:

console.log(Object.getOwnPropertyNames(Math)); //-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", . etc ] 

You can then use filter() to obtain only the methods:

console.log(Object.getOwnPropertyNames(Math).filter(function (p) < return typeof Math[p] === 'function'; >)); //-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", . etc ] 

In ES3 browsers (IE 8 and lower), the properties of built-in objects aren’t enumerable. Objects like window and document aren’t built-in, they’re defined by the browser and most likely enumerable by design.

Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:

• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes .
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.

I should point out that this means those objects aren’t enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the < DontEnum >attribute set on them.

Update: a fellow SO user, CMS, brought an IE bug regarding to my attention.

Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object’s prototype chain that has the attribute DontEnum.

In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for. in loop.

Источник

How can I list all the functions in my node js script?

I’ve tried looking at global , but it only contains variables, not functions. How can I list all the functions created in my script?

A custom AOP script that I’m creating for a node app. I want to use it for things like profiling, throttling, and custom security policies. I checked out Dojo but had some early probs just loading it into my node app so I thought I’d write a custom script. It shouldn’t be that hard.

So you want to do this from within the script itself? I’m not sure it’s so easy because you can have anonymous functions, functions inside closures, functions dynamically created etc.

6 Answers 6

Run node debug from command line with the file you want to look at. Then you can use list(some big number here)

node debug mini_file_server.js < debugger listening on port 5858 connecting. ok debug>scripts 26: mini_file_server.js debug> list(1000) 1 var http = require('http'), 2 util = require('util'), 3 fs = require('fs'); 4 5 server = http.createServer(function(req, res)< 6 var stream = fs.createReadStream('one.html'), 7 stream2 = fs.createReadStream('two.html'); 8 console.log(stream); 9 console.log(stream2); 10 stream.on('end', function()< 11 stream2.pipe(res, < end:false>); 12 >); 13 14 stream2.on('end', function()< 15 res.end("Thats all!"); 16 >); 17 18 res.writeHead(200, ); 19 stream.pipe(res, < end:false>); 20 stream2.pipe(res, < end:true>); 21 22 >).listen(8001); 23 >); debug> 

If the function has a name, it’ll show up in global just fine:

mb-work-laptop:~ markbessey$ node > for (var k in global) < console.log(k); >global process GLOBAL root Buffer setTimeout setInterval clearTimeout clearInterval console module require k > function z(a) < return a*10; >> for (var k in global) < console.log(k); >global process GLOBAL root Buffer setTimeout setInterval clearTimeout clearInterval console module require k z > > global.z [Function: z] 

I could have sworn I’d tested for this and found that functions weren’t available in global, but your script works fine for me too.

Sorry Mark I’ve demarked this as answer — it works fine in the console, but for the script function a() < return 1; >for(var k in global) console.log(k) it does not show the function ‘a’.

Right. As it turns out, in the interactive mode, those definitions go into global, but if you run a script from «node script.js», they end up as locals in the module. There’s definitely a way to get at that info from the debugger, but not sure if the script can access it.

This is impossible in node without more advanced reflecting tools like the debugger.

The only way to do this would be to use __parent__ which was removed due to security issues and other things. Like Mark Bessey said, when you run the script those variables become module closure variables. You can not access them elsewhere without explicitly exporting them.

This is not a bug, it’s by design. It’s just how node works. However, if you just ask your users to write function expression assignments, all would work a-ok:

Then, you can easily reflect on and enumerate module.exports and get all the function names.

There’s also https://github.com/c4milo/node-webkit-agent in the works which will be a more powerful version of node-inspector.

If you want to do some AOP, the route is AST.

You could build your own AOP framework with something like: http://esprima.org.

Or you could try node-burrito, excellent for not so complex aspects:

var burrito = require('burrito'); var src = burrito('someCall()', function (node) < if (node.name === 'call') node.wrap('qqq(%s)'); >); 

Wanted the exact thing you’re looking for. Couldn’t find any other solutions (most assumed use of «window» or «this» or «global», none of which will work for us in Node).

We can do it in about 25 lines with the help of a few libraries: fs, esprima, and escodegen.

const fs = require('fs'); const esprima = require("esprima"); const escodegen = require("escodegen"); 
  1. Let’s take the file this function is in, and first read it as text, just like any other file we would read as plain text
  2. We’ll use esprima to parse that text into a valid tree, part of which will contain our functions
  3. We’ll filter out that tree to only contain functions (except for this function we’re using to do this! We’re not after it)
  4. For that, we’ll need to grab the easy function declarations
  5. But ideally we can also grab any functions that were declared as variables with arrow expressions, which will take a little more work but is very doable.
  6. Next we want to reconstruct these objects from the tree back into actual usable functions in the code, so for all of our functions:
  7. Use escodegen to reconstruct that object into a string that looks just like written code for that function
  8. Convert that string into a usable function within the script itself again

The end result will spit back out an object with the key:value pairs where the key is the string of the function’s name, and the value is the function itself.

function getAllFunctionsInThisFileExceptThisFunction() < const thisFunctionName = arguments.callee.name; const rawTextFromThisFile = fs.readFileSync(__filename, "utf8"); const parsed = esprima.parseScript(rawTextFromThisFile); const allDeclaredVariables = parsed.body.filter(e=>e.type === "VariableDeclaration"); const allDeclaredFunctions = parsed.body.filter(e=>e.type === "FunctionDeclaration"); let allFunctions = [] for (declaredVariable of allDeclaredVariables) < const declarations = declaredVariable.declarations[0]; if (declarations.init.type === "ArrowFunctionExpression")< const anonymousFunction = declarations.init; let reconstructedFunction = anonymousFunction; reconstructedFunction.id = declarations.id; allFunctions.push(reconstructedFunction); >> allFunctions.push(. allDeclaredFunctions) const allFunctionsExceptThisOne = allFunctions.filter(e => e.id.name !== thisFunctionName); let functionsDict = <>; for (parsedFunction of allFunctionsExceptThisOne) < const functionString = escodegen.generate(parsedFunction); const newFunction = eval(`($)`) functionsDict[parsedFunction.id.name] = newFunction; > return functionsDict; > 

From there you can play away with it like any other object/dictionary.

const allFunctionsDict = getAllFunctionsInThisFileExceptThisFunction(); console.log( allFunctionsDict["sum"](10,30) ) //prints 40 console.log( allFunctionsDict["difference"](350,250) ) //prints 100 console.log( allFunctionsDict["product"](6,4) ) // prints 24 console.log( Object.keys(allFunctionsDict) ) //prints [ 'product', 'sum', 'difference' ] function sum(a, b) < return a + b; >function difference(a, b) < return a - b; >const product = (a,b) =>

Источник

Читайте также:  Php stream log file
Оцените статью