2013-12-22 30 views
2

我有這樣一段代碼(從「JavaScript的忍者的祕密」):的JavaScript子類代碼的解釋

(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(這更有意義?),它似乎工作正常。
+0

我認爲你的問題只是回答了我的問題[鏈接](http://stackoverflow.com/questions/20733249/ruby-code-blocks-versus-javascript-anonymous-functions-distiction) – ialexander

回答

2

爲什麼Class.constructor = Class

我不知道,這沒有任何意義。它可能應該是proto.constructor = Class;

爲什麼我們有Class.subClass = arguments.callee?我嘗試使用Class.subClass = Object.subClass(這更有意義?),它似乎工作正常。

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

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