【问题标题】:Why does John Resig re-declare the original _super, after using inherited _super?为什么 John Resig 在使用继承的 _super 后重新声明原始的 _super?
【发布时间】:2016-10-17 11:41:07
【问题描述】:

取自: https://stackoverflow.com/a/15052240/1487102

向下滚动查看我感兴趣的台词

有道理他在申请前声明了继承函数this._super

我不明白的是:在他执行函数并获得返回值之后,他为什么将this._super 替换为之前的内容??

评论说只需要临时声明,但为什么不声明呢?我看不出垃圾收集将如何改进,或任何其他优化。

/* Simple JavaScript Inheritance for ES 5.1
 * based on http://ejohn.org/blog/simple-javascript-inheritance/
 *  (inspired by base2 and Prototype)
 * MIT Licensed.
 */
(function(global) {
  "use strict";
  var fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  function BaseClass(){}

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

    // Set up the prototype to inherit from the base class
    // (but without running the init constructor)
    var proto = Object.create(_super);

    // Copy the properties over onto the new prototype
    for (var name in props) {
      // Check if we're overwriting an existing function
      proto[name] = typeof props[name] === "function" && 
        typeof _super[name] == "function" && fnTest.test(props[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;  // <------ why??
              return ret;
            };
          })(name, props[name])
        : props[name];
    }

    // The new constructor
    var newClass = typeof proto.init === "function"
      ? proto.hasOwnProperty("init")
        ? proto.init // All construction is actually done in the init method
        : function SubClass(){ _super.init.apply(this, arguments); }
      : function EmptyClass(){};

    // Populate our constructed prototype object
    newClass.prototype = proto;

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

    // And make this class extendable
    newClass.extend = BaseClass.extend;

    return newClass;
  };

  // export
  global.Class = BaseClass;
})(this);

【问题讨论】:

    标签: javascript inheritance resig


    【解决方案1】:

    this 所指的内容有点困惑

    在声明this._super = function时,整个类实例会有一个键_super,它指向一个特定的函数(显然不需要)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 2013-02-09
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 2016-05-17
      相关资源
      最近更新 更多