Javascript子类代码解释

Javascript子类代码解释,javascript,object,constructor,Javascript,Object,Constructor,我有一段代码(来自“Javascript忍者的秘密”): 我很难理解两件事: 为什么Class.constructor=Class? 为什么我们需要覆盖它呢?我试着把它评论出来,效果非常好 为什么我们有Class.subClass=arguments.callee? 我试着使用Class.subClass=Object.subClass(哪个更有意义?),它似乎工作得很好 为什么Class.constructor=Class 我不知道,这没有任何意义。它可能应该是proto.constructo

我有一段代码(来自“Javascript忍者的秘密”):

我很难理解两件事:

  • 为什么
    Class.constructor=Class

    为什么我们需要覆盖它呢?我试着把它评论出来,效果非常好
  • 为什么我们有
    Class.subClass=arguments.callee

    我试着使用
    Class.subClass=Object.subClass
    (哪个更有意义?),它似乎工作得很好
  • 为什么
    Class.constructor=Class

    我不知道,这没有任何意义。它可能应该是
    proto.constructor=Class

    为什么我们有
    Class.subClass=arguments.callee
    ?我试着使用
    Class.subClass=Object.subClass
    (哪个更有意义?),它似乎工作得很好

    是的,他就是这个意思<代码>参数。被调用方
    已被弃用,但具有相同的效果。你的版本更好


    你也可以看看。

    我想你的问题正好回答了我的问题
    (function() {
      var initializing = false,
          superPattern = /xyz/.test(function() { xyz; }) ? /\b_super\b/ : /.*/;
    
      Object.subClass = function(properties) {
        var _super = this.prototype;
    
        initializing = true;
        var proto = new this();
        initializing = false;    
    
        for (var name in properties) {
    
          proto[name] = typeof properties[name] == "function" &&
                        typeof _super[name] == "function"     && 
                        superPattern.test(properties[name])   ?
            (function(name, fn) {
              return function() {
                var tmp = this._super;
    
                this._super = _super[name];
    
                var ret = fn.apply(this, arguments);
                this._super = tmp;
    
                return ret;
              };
            })(name, properties[name])
            :
            properties[name];
        }
    
        function Class() {
          if (!initializing && this.init) {
            this.init.apply(this, arguments);
          } 
        }  
    
        Class.prototype = proto;
        Class.constructor = Class;                // Why do we need this?
        Class.subClass = arguments.callee;        // Why is this not Object.subClass?
        return Class;
    
      };
    
    })();
    
    var Person = Object.subClass({
      init: function(isDancing) {
        this.dancing = isDancing;
        return true;
      },
      dance: function() {
        return this.dancing;
      }
    });
    
    var person = new Person(true);
    alert (person.dance());