Weird regex in inherit.js (from John Resig) - why, what and how?

I recently used a small useful library from John Resig called inherit.js . Usually I try to understand the main parts of the libraries that I use, and after a lot of scratches on my head, I finally understood the hard bits of the code (namely, how it could call the corresponding superclass method).

1% of the bit that I don't get is related to regex

fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; 
  • The regular expression / xyz / is checked for a function. Both MSDN and MDN state that test takes a string as an argument. There is no mention of the function, but since there are no errors in the console, I think it should fly, but how does it work?
  • The next WTF is that the body of the function is xyz; . This function cannot be executed, because otherwise it will lead to " ReferenceError: xyz is not defined ". Correctly? So what is he doing?
  • If the test result is true, then fnTest is equal to a regular expression that checks for _super at the word boundary, otherwise a regular expression that matches something. Dual WTF; again how and why.

Later, there is a related bit of code that uses this regular expression.

  // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? aFunctionThatCanCallSuper /* Lots of code */ : prop[name]; 

Bit, I wonder, here is fnTest.test(prop[name]) . I understand that all other tests that check if a property exists are a function, etc., but not what the regular expression test does. Is anyone

+7
source share
1 answer

that :

test only accepts strings as input, so the function will be toString ed, like any other object, not a string. xyz not interpreted as a variable, but as a string, so it will not cause a reference error. This happens in other places, for example:

 var a = function(){}; var b = function(){}; console.log(a + b); // `+` coerces with `toString` 

why :

Serializing functions in older browsers is unreliable and may not output the _super property to the function body, but (I assume) something like function{[native code]} or [object Object] ; in such cases, use a regular expression such as /.*/ to match something and not perform optimizations that may be performed in browsers that display the correct result.

Related links:

http://blog.buymeasoda.com/understanding-john-resigs-simple-javascript-i/ (found by Andreas)
http://es5.imtqy.com/x15.3.html#x15.3.4.2
http://bytes.com/topic/javascript/answers/747203-function-tostring

+6
source

All Articles