Javascript 中的函数可序列化性

Function serializability in Javascript?

本文关键字:序列化 函数 Javascript      更新时间:2023-09-26

我正在读一本书(Secrets.of.the.JavaScript.Ninja),其中提出了一种用于完成继承方案的语法。

这将允许我做:

var Person = Object.subClass(
{
          init: function (isDancing)
          {
              this.dancing = isDancing;
          } 
});

var Ninja = Person.subClass(
{
    init: function ()
    {
        this._super(false);
    } 
});

这是实现代码:

/*1*/   (function ()
/*2*/   {
/*3*/       var initializing = false,
/*4*/           superPattern =
/*5*/               /xyz/.test(function ()   {   xyz; }) ? /'b_super'b/ : /.*/;
/*6*/     
/*7*/       Object.subClass = function (properties)
/*8*/       {
/*9*/           var _super = this.prototype;
/*10*/           initializing = true;
/*11*/           var proto = new this();
/*12*/           initializing = false;
/*13*/           for (var name in properties)
/*14*/           {
/*15*/               proto[name] = typeof properties[name] == "function" &&
/*16*/                   typeof _super[name] == "function" &&
/*17*/                   superPattern.test(properties[name]) ?
/*18*/                   (function (name, fn)
/*19*/               {
/*20*/                   return function ()
/*21*/                   {
/*22*/                       var tmp = this._super;
/*23*/                       this._super = _super[name];
/*24*/                       var ret = fn.apply(this, arguments);
/*25*/                       this._super = tmp;
/*26*/                       return ret;
/*27*/                   };
/*28*/               })(name, properties[name]) :
/*29*/                   properties[name];
/*30*/           }
/*31*/   
/*32*/           function Class()
/*33*/           {
/*34*/               // All construction is actually done in the init method
/*35*/               if (!initializing && this.init)
/*36*/   
/*37*/                   this.init.apply(this, arguments);
/*38*/           }
/*39*/           Class.prototype = proto;
/*40*/           Class.constructor = Class;
/*41*/           Class.subClass = arguments.callee;
/*42*/           return Class;
/*43*/       };
/*44*/   })();

我的问题是关于#5行:

我知道:test()方法需要一个字符串,这会触发函数的toString()方法

但是他为什么不使用简单的toString方法呢?

function getStringFromFunction(fn)
{
  return fn.toString();      
}

我错过了什么?我很确定使用这个正则表达式而不是简单的字符串是有原因的......

我想他关心的是这个问题:http://my.opera.com/hallvors/blog/show.dml/1665828 因为作者明确指出了约翰·雷西格。

同时Function.prototype.toString()它是 ECMAScript 规范的一部分,根据这个答案,它使用起来非常安全。