我正在John Resig的类继承实现(javascript)之上构建一个系统
所有工作都很好,除了为了检查/调试的目的(也许是为了以后的类型检查),我希望对实例化类的实际名称有一个句柄。
e。g:以约翰为例,返回Ninja
,而不是Class
。
我知道这个名字来自this.__proto__.constructor.name
,但这个道具是只读的。我猜它必须是子类本身初始化的一部分。
有人知道吗?
如果仔细查看代码,您会看到像这样的几行:
Foo.prototype = new ParentClass;//makes subclass
Foo.prototype.constructor = Foo;
如果省略第二行,则构造函数的名称将是父类的名称。name属性可能是只读的,但是prototype
不是,原型的constructor
属性也不是。这就是如何设置"类"/构造函数的名称。
还要注意__proto__
不是获取对象原型的方法。最好使用以下代码片段:
var protoOf = Object && Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.prototype;
//obviously followed by:
console.log(protoOf.constructor.name);
//or:
protoOf.addProtoMethod = function(){};//it's an object, thus protoOf references it
//or if all you're after is the constructor name of an instance:
console.log(someInstance.constructor.name);//will check prototype automatically
就这么简单,真的