原型继承。 obj-> C-> B-> A,但是obj.constructor是A.为什么? [英] Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why?

查看:115
本文介绍了原型继承。 obj-> C-> B-> A,但是obj.constructor是A.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var print = function(text){
  document.write(text);
  document.write("</br>");
}

var A = function(){
}
A.prototype.name="A";

var B = function(){
}
B.prototype = new A();
B.prototype.name="B";

var C = function(){
}
C.prototype = new B();
C.prototype.name="C";

obj = new C();
print(obj.name);
print(obj.constructor.prototype.name);
print(obj.constructor == A);

此代码给出下一个输出:

This code gives next output:

C
A
true

为什么obj.constructor这里是A而不是C?

Why obj.constructor here is A and not C ?

推荐答案

此代码示例,您必须在使用继承时手动重置 .constructor 属性,否则您的构造函数将被覆盖当你打电话新A()新B()

As seen in this code sample, you have to manually reset the .constructor property when using inheritance, or your constructor is being overridden when you call new A() or new B():

B.prototype = new A();
B.prototype.constructor = B; // need this line to fix constructor with inheritance

这是一个工作样本:http://jsfiddle.net/93Msp/

希望这会有所帮助!

这篇关于原型继承。 obj-&gt; C-&gt; B-&gt; A,但是obj.constructor是A.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆