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.
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.
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.
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] }.
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.