我正在使用 Resig 的 Simple JavaScript Inheritance创建我的类(class)。到目前为止,我唯一不喜欢的是,当我将使用该库创建的对象记录到控制台时,它的名称只是“类”。我的问题是是否有办法修改他的代码,以便我在控制台中获取实际的类名。以下是来自 Chrome 控制台的示例:
我真的很希望这个名称“Class”是我创建的类的实际名称,就像您执行以下操作时那样:
我相信我知道发生这种情况的原因是 Resig 的库:实际的构造函数只是简单地命名为“Class”。这是他的库的代码:
(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;
};
})();
您会在大约 2/3 的位置找到 Class()
函数。有谁知道如何修改此代码以便您在控制台中获得类的实际名称?
最佳答案
在创建 Person
时对 Person.prototype.constructor
进行更改:
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
关于javascript - 使用 Resig 的简单 JavaScript 继承时,让类名显示在控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7904321/