Is it possible to check if a function is a javascript function or a specific developer function?

Given the function, I would like to know if it is a developer-defined function or a built-in function provided by the JavaScript engine. Is it possible?

For a developer-defined function, I would like to track its execution.

+2


a source to share


3 answers


The method valueOf

you specify in your own will not work as you mention it.

Function.prototype

doesn't have a method valueOf

, it inherits from Object.prototype

, and this method will just return the same function object where you call it:

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

      

I think you are mixing it with the toString method (or you are calling the valueOf method call, which invokes the implicit conversion of ToString in most browsers).



However, you can use the method toString

directly on function objects and in almost all implementations will return you the string representation containing "[native code]"

the function body in its body, I would not 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 method toString

for functions, for example, some mobile browsers will return the same string for any function object.

+2


a source


I have a solution on my own --- using the valueOf () method.

Copied and pasted the following :

The valueOf method returns a string that represents the source code for the 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 machine (make, model, year) {this .make = make, this .model = model, this.year = year

With the built-in Function object, the valueOf method will create the following line:

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

+3


a source


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

+2


a source







All Articles