如果重新分配了原型和构造函数,如何获取实例名称

How to get instance name if you reassigned the prototype and constructor?

本文关键字:何获取 实例 获取 新分配 分配 如果 原型 构造函数      更新时间:2023-09-26

如果我有以下内容:

function Constructor1(data){
...
...
...};

function Constructor2(data){
Constructor1.prototype.constructor.call(this, data);
...
...
...
}
Constructor2.prototype = new Constructor1();

那么,我以后如何确定它们是如何构建的呢?我知道我可以做if(Constructor2的testObject实例),但如果我有很多继承的对象,我不想对所有东西都做那个测试。有没有办法以某种方式返回字符串"Constructor2"?(或者调用的第一个构造函数)是什么?

  1. 您可以这样调用父级:parent.call(this,args)
  2. 您不应该创建Parent的实例来设置Child中继承的原型部分

如果在不破坏Child中的prototype.constructor的情况下设置原型,则可以使用构造函数的name属性:

function Parent(args){
};
function Child(args){
  Parent.call(this,args);
};
console.log(Child.prototype.constructor.name);//=Child
//overwrithing Child.prototype so also Child.prototype.constructor
Child.prototype=Object.create(Parent.prototype);
console.log(Child.prototype.constructor.name);//=Parent, needs to be fixed
Child.prototype.constructor=Child;//fixed
var c = new Child();
console.log(c.constructor.name);//=Child

Function的name属性不是标准的,因此不能保证它的行为:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

您可能需要使用函数本身进行检查:(this.constructor===Parent)

这里有更多关于构造函数和原型的信息。