everconfusedGuy
everconfusedGuy

Reputation: 2797

How to find if a function is inbuilt function or user-defined

Lets say if I have a function a. I would like to know if its inbuilt function or a function defined by the user.
I have tried checking if a.toString() has [native code] in it but user-defined functions which have the substring [native code] would fail. Is there any better way of doing this?

Upvotes: 2

Views: 99

Answers (2)

tenbits
tenbits

Reputation: 8008

So, here some code to check:

var rgx = /\[native code\]\s*\}\s*$/;

function some(){
    '[native code]'
}

console.log(
    rgx.test(print.toString()),
    rgx.test(some.toString())
);

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

One, perhaps naive, approach would be to test whether the function name exists a property of the document:

function newFunction (){
    return true;
}

console.log('newFunction' in document, 'toString' in document);

This is, of course, not exhaustively tested and does fail if the function is created as an extension of a prototype, for example:

function newFunction (){
    return true;
}

Object.prototype.newFunctionName = function () {
    return 10 * 2;
};

console.log('newFunction' in document, 'toString' in document, 'newFunctionName' in document); // false, true, true

JS Fiddle demo.

Given that it also fails for 'eval' in document (in that it returns false), then this will, or can, only work to identify prototype-methods of the Objects. Which is, at best, an incomplete solution.

Upvotes: 1

Related Questions