解析John Resig Simple JavaScript Inheritance代码(2)

将当前对象的原型对象存储在 _super中. this.prototype是被扩展对象的原型, 它可以访问父级方法在你需要的地方,  这个变量叫什么 _super , 是因为 super 是保留字. 尽管现在还没有应用起来.

复制代码 代码如下:


initializing = true;var prototype = new this();initializing = false;

实例 class 对象存储在 prototype 变量中, 但不执行 init 方法. 之前设置 initializing 为 true 所以在 new Class的时候 不会 fire init 方法. prototype变量分配后, initializing 被设置回 false, 为了下一步可以正常工作. (e.g 当想要创建一个真正的实例的时候)

复制代码 代码如下:

   
for (var name in prop) { // ...}

使用一个 for 循环, 我们迭代出 prop 里的属性和方法. 该属性是通过 extends 方法传递进来的, 除了一些对 _super 的特殊处理, 我们将值赋给 prototype 属性.

复制代码 代码如下:

   
prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() {  // special handling for _super }; })(name, prop[name]) : prop[name];

当我们遍历 prop 里的每个对象时, 如果 满足 (typeof prop[name] == "function")  (typeof _super[name] == "function") (fnTest.test(prop[name]) == true)
我们将会加入新的方法来处理 绑定到 父类 新的方法 以及 原始方法.
        以上方式代码 看起来可能很有些 混乱 下面改使用 一种清晰的方式查看一下.

复制代码 代码如下:

    
if (typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])) { prototype[name] = (function(name, fn){ return function() {  // special handling for _super }; })(name, prop[name]);} else { // just copy the property prototype[name] = prop[name];}

另一个自执行匿名函数, 在处理 super 中的 name prop[name] 被使用 . 没有这个闭包. 当返回这个function时 这个变量的引用将会出错.(e.g 它始终会返回 循环的最后一个)
        遍历所有, 我们将返回一个新的函数, 这个函数来处理 原生方法(via super) 和 新方法.

复制代码 代码如下:

       
// special handling for supervar tmp = this._super;this._super = _super[name];var ret = fn.apply(this, arguments);this._super = tmp;return ret;

对 super 的特殊处理, 我们首先要存储 已存在 _super 属性和类的一些参数. 存储在 临时 tmp 里, 这是为了防止 _super 中已存在的方法被重写
完事儿后我们将 tmp 在赋给 this._super 这样它就可以正常工作了.
         下一步, 我们将 _super[name] 方法赋给 当前对象的 this._super, 这样当 fn 通过 apply 被执行的时候 this._super()就会指向 父类方法, 这个
父类方法中的 this 也同样可以访问 当前对象.
         最后我们将返回值存储在 ret 中, 在将 _super 设置回来后返回该对象.
        下面有个简单的例子,  定义个简单的 Foo , 创建继承对象 Bar:

复制代码 代码如下:


var Foo = Class.extend({ qux: function() { return "Foo.qux"; }});var Bar = Foo.extend({ qux: function() { return "Bar.qux, " + this._super(); }});

当 Foo.extends 被执行, 在 qux 方法中由于存在 this._super 所以 Bar原型上的qux 实际上应该是这样的:

复制代码 代码如下:

      
Bar.prototype.qux = function () { var tmp = this._super; this._super = Foo.prototype.qux; var ret = (function() { return "Bar.qux, " + this._super(); }).apply(this, arguments); this._super = tmp; return ret;}

在脚本中完成这步后, 构造方法将被调用

复制代码 代码如下:


function Class() { if ( !initializing && this.init ) this.init.apply(this, arguments);}

这段代码调用 Class 创建一个新的构造方法, 这不同于之前创建的 this.Class, 作为本地的 Class.extend. 这个构造方法返回 Class.extend 的调用(比如之前 Foo.extends).  new Foo() 实例后这个构造方法将被执行.
        构造方法将会自动执行 init() 方法(如果存在的话) 正好上面说的那样, 这个 initializing 变量来控制 init 是否被执行.

复制代码 代码如下:

      
Class.prototype = prototype;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wddfsg.html