Получение имени класса для отображения в консоли при использовании Resig's Simple JavaScript Inhertiance - PullRequest
3 голосов
/ 26 октября 2011

Я использую Resig's Simple JavaScript Inheritance для создания своих классов.Пока что мне не нравится в этом то, что когда я записываю объект, созданный с помощью этой библиотеки, на консоль, его имя просто «Класс».Мой вопрос заключается в том, есть ли способ изменить его код, чтобы вместо этого я получил фактическое имя класса в консоли.Вот пример из консоли Chrome:

enter image description here

Мне бы очень хотелось, чтобы это имя "Class" было реальным именем класса, который я создал, так, как если быВы сделали следующее:

enter image description here

Мне кажется, я знаю причину, по которой это происходит с библиотекой Ресига: фактическая функция конструктора просто называется «Класс».Вот код для его библиотеки:

(function(){
  var initializing = false,
    // Determine if functions can be serialized
    fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // Create a new Class that inherits from this class
  Object.subClass = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var proto = new this();
    initializing = false;

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

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

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

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

    // And make this class extendable
    Class.subClass = arguments.callee;

    return Class;
  };
})();

Вы найдете функцию Class() примерно на 2/3 пути вниз.Кто-нибудь знает, как изменить этот код, чтобы вы получили фактическое имя класса в консоли?

1 Ответ

3 голосов
/ 26 октября 2011

Внесите изменения в Person.prototype.constructor при создании Person:

var Person = (function() {
  var myConstructor = Class.extend({
    init: function(isDancing){
      this.dancing = isDancing;
    },
    dance: function(){
      return this.dancing;
    }
  });
  myConstructor.prototype.constructor = function Person(){};
  return myConstructor;
}());

Я не думаю, что вы могли бы сделать это из Simple JavaScript Inheritance.Вам нужно, чтобы Person.prototype.constructor была именованной функцией, и я не думаю, что вы можете назвать функцию без eval ... и у вас слишком много представителей, чтобы я мог объяснить, почему вы не должны этого делать;)


Никаких обещаний, это ни к чему не приводит, однако: P

...