I recently used a little utility library by John Resig, called inherit.js. I usually try to understand the core parts of the libraries I am using, and after a lot of head scratching I finally understood the hard bits of the code (namely how he could call the corresponding method of the super class).
The 1% bit I do not get is related to a regex
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
- The regex /xyz/ is tested against a function. Both MSDN and MDN state that
test
takes a string as the argument. No mention of a function, but since there are no errors in the console, I guess it must fly, but how does it work? - The next WTF is that the function body is
xyz;
. This function cannot be executed, because it would otherwise result in a "ReferenceError: xyz is not defined
". Right? So what does it do? - If the result of the test is true, then
fnTest
is equal to a regex which checks for_super
on a word boundary, else a regex that matches on anything. Double WTF; again how and why.
Later on there is a related bit of code, where this regex is being used.
// 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];
The bit I am wondering about here is fnTest.test(prop[name])
. I understand all the other tests, which check if the property exists, is a function, etc, but not what the regex test does. Anyone?