如果重新分配了原型和构造函数,如何获取实例名称
How to get instance name if you reassigned the prototype and constructor?
如果我有以下内容:
function Constructor1(data){
...
...
...};
function Constructor2(data){
Constructor1.prototype.constructor.call(this, data);
...
...
...
}
Constructor2.prototype = new Constructor1();
那么,我以后如何确定它们是如何构建的呢?我知道我可以做if(Constructor2的testObject实例),但如果我有很多继承的对象,我不想对所有东西都做那个测试。有没有办法以某种方式返回字符串"Constructor2"?(或者调用的第一个构造函数)是什么?
- 您可以这样调用父级:parent.call(this,args)
- 您不应该创建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)
这里有更多关于构造函数和原型的信息。
相关文章:
- 使用jQuery获取Dropzone实例/对象
- 如何在速度模板中获取LiferayPortlet实例id
- 如何获取单选按钮的多个实例的选定单选按钮值
- 无法在XUL Firefox扩展中获取TinyMCE的实例
- 如何在另一个组件中获取指令/组件实例
- 如何从一个友好的iframe中获取iframe实例
- 更新Redux状态&然后在同一实例中获取更新状态
- 从对象实例中获取变量名称
- 可以获取模板实例值,但不能将其用于其他函数
- 突出显示所选文本并同时获取实例
- 如何获取先前创建的Google图表的实例
- 获取JSON标记(JAVASCRIPT)中的所有JSON实例
- jquery获取类的下一个实例的值
- 如何在 JavaScript 中获取实例名称
- 如何在angularjs中获取实例函数
- Jquery 获取实例并将其写入输入字段
- Javascript:如何获取实例的名称
- AJAX请求可以't从Rails应用程序中的控制器获取实例变量
- $uibModal:从方法中获取实例
- 如果重新分配了原型和构造函数,如何获取实例名称