javascript - 奇怪的 JavaScript 习语 - "/xyz/.test(function(){xyz;})"是做什么的?

标签 javascript regex function

John Resig 写了一个漂亮的 Class 函数,时髦。我试图弄清楚发生了什么,除了一行之外,几乎所有的东西都弄清楚了:

fnTest = /xyz/.test(function () {xyz;}) ? /\b_super\b/ : /.*/;

我立刻想到了一些事情,首先 xyz 从未被初始化为变量;那为什么会这样呢?其次,为什么要针对不返回任何内容(无返回语句)的内容测试 /xyz/。除非有一些我不知道的 javascript 的漂亮属性(这是可能的,我认为自己相当擅长 JS,并且可以解释我遇到的大部分代码,但这并不意味着我在同一个山上. John Resig 称之为家的珠穆朗玛峰大小)。

对于那些好奇的人,这是来自 john resigs 网站的完整未经编辑的代码 John Resig Simple Javascript Inheritance :

(function () {
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);       
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };

})();

最佳答案

这只是检查“函数反编译”是否有效的一种快速而肮脏的方法。

RegExp.prototype.test 方法将获取参数并将其转换为字符串,永远不会评估函数内的 xyz 引用。

为什么要检查这个?

因为 Function.prototype.toString 方法返回函数的依赖实现表示,在某些实现中,例如较旧的 Safari 版本、Mobile Opera 和一些黑莓浏览器,它们实际上不会返回任何有用的信息。

关于javascript - 奇怪的 JavaScript 习语 - "/xyz/.test(function(){xyz;})"是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3911690/

相关文章:

javascript - 单击按钮运行功能 - 不起作用?

javascript - 根据三个模型属性对 Backbone 集合进行排序

regex - 使用 Python 正则表达式从字符串中提取月份和年份

C# 正则表达式不起作用

r - 从字符串中提取某些数字

php - 从文件中删除扩展名

Javascript 尝试让 Function 出现在 Alert 中

javascript - 如果我在 Keydown 事件中设置断点,我输入的键将不会附加到文本框

javascript - 如何让 jQuery 从上一个位置动画到新位置?

javascript - 关于禁用按钮解决方法的 Bootstrap 工具提示