7

我最近使用了John Resig的一个小实用程序库,称为inherit.js。我通常尝试理解我正在使用的库的核心部分,经过一番摸索,我终于理解了代码的难点(即他如何调用超类的相应方法)。

我没有得到的 1% 位与正则表达式有关

fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  1. 正则表达式 /xyz/ 针对函数进行测试。MSDNMDN状态都test将字符串作为参数。没有提到一个功能,但由于控制台没有错误,我猜它必须飞,但它是如何工作的?
  2. 下一个 WTF 是函数体是xyz;. 该函数无法执行,否则会导致“ ReferenceError: xyz is not defined”。正确的?那么它有什么作用呢?
  3. 如果测试结果为真,则fnTest等于检查_super单词边界的正则表达式,否则是匹配任何内容的正则表达式。双WTF;再次如何以及为什么。

稍后有一段相关的代码,正在使用这个正则表达式。

  // 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];

我想知道的一点是fnTest.test(prop[name])。我了解所有其他测试,它们检查属性是否存在、是否是函数等,但不了解正则表达式测试的作用。任何人?

4

1 回答 1

6

The what:

test only takes strings as input, so a function will be toStringed, like will any other object that's not a string. xyz is not interpreted as a variable, but as a string, so it won't throw a reference error. This happens in other places as well, take this for example:

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

The why:

The serialization of functions in old browsers is not reliable and might not output the _super property in the function's body, but (I'm assuming) something like function{[native code]} or [object Object]; in those cases use a regex such as /.*/ to match anything and not perform the optimizations that can be done in browsers that output the correct result.

Related links for more info:

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

于 2013-06-21T06:15:48.567 回答