Paul
Paul

Reputation: 1014

Is it possible to check whether a function is a javascript function or a developer defined function?

Given a function, I'd like to know whether it's a developer-defined function or a built-in function provided by JavaScript engine. Is it possible?

For a developer-defined function, I'd like to trace its execution.

Upvotes: 2

Views: 157

Answers (3)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827486

The valueOf method you mention in your own answer will not work as you mention it.

The Function.prototype doesn't have a valueOf method, it is inherited from Object.prototype and this method will simply return the same function object where you call it:

Function.valueOf() === Function; // true

I think you are confusing it with the toString method (or you are alerting the valueOf method call which causes on most browsers an implicit ToString conversion).

However, you can use the toString method directly on function objects, and in almost all implementations, will return you a string representation containing "[native code]" in its function body, I wouldn't recommend it too much because, the Function.prototype.toString method is implementation dependent...

function isNative(fn) {
  return /native code/.test(fn.toString);
}

isNative(Function); // true
isNative(function () {}); // false

Again I advise you that there are some browsers that will return different results when using the toString method on functions, for example, some Mobile browsers will return the same string for any function object.

Upvotes: 2

Paul
Paul

Reputation: 1014

I've got a solution by myself---using the valueOf method().

Copied and pasted the following:

The valueOf method returns a string which represents the source code of a function. This overrides the Object.valueOf method. The valueOf method is usually called by JavaScript behind the scenes, but to demonstrate the output, the following code first creates a Function object called Car, and then displays the value of that function:

Code: function car(make, model, year) {this.make = make, this.model = model, this.year = year} document.write(car.valueOf())

Output: function car(make, model, year) {this.make = make, this.model = model, this.year = year

With the built-in Function object the valueOf method would produce the following string:

Output: function Function() { [native code] }.

Upvotes: 3

Jeff Meatball Yang
Jeff Meatball Yang

Reputation: 39037

In a general sense, no. Javascript built-in objects and functions do not have (or lack) any special property that can be tested at runtime that guarantees it is not a developer-defined function. All methods and objects can be overridden by the developer.

Upvotes: 2

Related Questions