0

から取得: 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);
4

1 に答える 1

0

this何が参照されているかについての少しの混乱

を宣言するthis._super = functionと、クラス インスタンス全体が_super特定の関数を指すキーを持ちます (明らかに望ましくありません)。

于 2016-06-16T06:30:46.443 に答える