• 奇怪正则匹配的test函数


    在John Resig 那篇关于在JavaScript中实现简单继承的文章中,有这样一段代码:

    var fnTest = /xyz/.test(function(){xyz;}) ? /b_superb/ : /.*/;

    对于其中正则表达式匹配函数test的用法,我很是迷惑:

    /xyz/.test(function(){xyz;})

    我查阅了Mozilla developer center中关于test函数的描述:

    Executes the search for a match between a regular expression and a specified string. Returns true or false.

    字符串中是否有匹配正则表达式的子字符串。返回true或false。

    其语法格式:

    regexp.test([str])

    注意这里的参数是字符串,根本没有提到test函数的参数可以是函数的说法。

    我试着修改这段奇怪的代码,得到了一些运行结果:

    /xyz/.test("xyz"); // true
    /xyz/.test(function(){"xyz";}); // false
    /xyz/.test(function(){return "xyz";}); // true
    /xyz/.test(function(){return xyz;}); // true
    /xyz/.test(function(){return axyz;}); // true
    /xyz/.test(function(){return "axyz";}); // true
    /xyz/.test(function(){return "xayz";}); // false

    怎么回事?

    华丽的分割线
    =======================================
    我终于知道了,却原来在test内部进行了类型转换,下面代码:

    /xyz/.test(function(){xyz;});

    等价于:

    /xyz/.test((function(){xyz;}).toString());

    又等价于:

    /xyz/.test("function(){xyz;}");

    那么为什么下面的代码返回false呢?

    /xyz/.test(function(){"xyz";});

    我们执行下这行代码就知道了:

    // 这行代码的执行结果是:"function(){}"
    (function(){"xyz";}).toString();

    所以我们可以写出更加诡异的代码来迷惑大家了 :)

    /function/.test(function(){}); // true
    // b 表示文字边界(对英文而言的)
    /b_superb/.test(function(){this._super();}); // true

  • 相关阅读:
    redis-原理-对象-列表对象(八)
    分布式事物-Saga
    分布式事物-本地消息表
    分布式事物-TCC
    分布式事物-XA协议
    Spring Boot-多环境配置(十)
    maven-maven-resources-plugin插件使用
    maven-assembly-plugin插件使用
    20201207 徐艺铭 《信息安全导论》第三周学习总结
    20201207 徐艺铭 第二周学习总结
  • 原文地址:https://www.cnblogs.com/sanshi/p/1519585.html
Copyright © 2020-2023  润新知