In JavaScript, native functions can be identified when coerced to string, for example:
console.log(document.getElementById);
// prints "function getElementById() { [native code] }"
However, any function can overload toString()
and pretend to be native:
function sum(a, b) {
return a + b;
}
console.log(sum);
// prints "function sum(a, b) { return a + b; }"
sum.toString = function() { return 'function sum() { [native code] }'; };
console.log(sum);
// now prints "function sum() { [native code] }"
I was looking through the source code of Zone.js and found this bit, which does exactly that (and by design, according to one of the tests):
class ZoneAwarePromise<R> implements Promise<R> {
static toString() {
return 'function ZoneAwarePromise() { [native code] }';
}
...
Now, I'm not asking for speculation on why the Zone.js team in particular chose to do this (I couldn't find any official blog post / explanation), but rather:
In general, when would you want to do this? Are there any advantages to doing it?
Are there any sideeffects to it, i.e. does the JavaScript standard or any JavaScript engine treat these functions differently?
Native Function APIs are JavaScript wrappers for Objective C and Android native APIs. They are generated from the source APIs, which means that they can be updated and released quickly when the target API changes. This gives you the flexibility to update your apps quickly.
What Does Native Code Mean? Native code refers to programming code that is configured to run on a specific processor. Native code will generally not function if used on a processor other than the one it was specifically written for unless it is allowed to run over an emulator.
The code you are inspecting is specific to Chromium engines and MS Edge.
function eval() { [native code] }
In Firefox and Safari, the string representation of the same function looks rather like:
function eval() {
[native code]
}
In Internet Explorer, the string representation is similar, except that there are also newlines at the beginning and at the end of the string.
So if that code is supposed to fake a native function, at least it's not doing it well (or maybe it's Node specific?).
I'm not aware of any practical uses for this, except for porting JSFuck across browsers.
A safer way to determine if a function is native is taking the result of Function.prototype.toString.call(fn)
(where fn
is the function being tested) and search for the string [native code]
at the expected position. This is an invariant in all browsers, although it hasn't done it to the spec, as far as I know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With