【问题标题】:Javascript subclass code explanationJavascript子类代码解释
【发布时间】:2014-01-11 01:21:24
【问题描述】:

我有这段代码(来自“Javascript Ninja 的秘密”):

(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());

我很难理解两件事:

  1. 为什么是Class.constructor = Class
    为什么我们需要重写它?我尝试将其注释掉,效果非常好。
  2. 为什么我们有Class.subClass = arguments.callee
    我尝试使用Class.subClass = Object.subClass(这更有意义?),它似乎工作正常。

【问题讨论】:

  • 我认为你的问题刚刚回答了我的问题link

标签: javascript object constructor


【解决方案1】:

为什么是Class.constructor = Class

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

为什么我们有Class.subClass = arguments.callee?我尝试使用Class.subClass = Object.subClass(这更有意义?),它似乎工作正常。

是的,这就是他的意思。 arguments.callee 已弃用,但效果相同。你的版本更好。

你也可以看看Is John Resig's Javascript inheritance snippet deprecated?

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 2012-04-07
    • 2015-07-31
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    相关资源
    最近更新 更多