本文介绍了原型继承的构造函数赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在进行原型继承时,会要求将子构造函数引用回自身,
When making the prototypal inheritance, it's asked to refer the child's constructor back to itself below,
A = function() {}
B = function() {}
B.prototype = new A;
B.prototype.constructor = B;
如果不是会产生什么不利影响?
What would take adverse effect if not?
编辑
- 作为
@GGG
&@CMS
已经解释过,构造函数对齐对于通过new Child(...)$创建子对象没有
效果c $ c>,但是后来正确反映子对象的构造函数所需的是
。 -
@GGG
也有建议作为原型链扩展
的防御性替代方案。而Child.prototype = new Parent(...)
包括父级的子属性,Child.prototype =
没有。
Object .create(Parent.prototype)
- As
@GGG
&@CMS
have explained, the constructor alignment takes noeffect on creating the child object bynew Child(...)
, but isnecessary to correctly reflect the child object's constructor later. @GGG
has also suggested a defensive alternative to extendthe prototype chain. WhileChild.prototype = new Parent(...)
includes parent's properties to child,Child.prototype =Object.create(Parent.prototype)
doesn't.
推荐答案
首先,请不要这样做:
B.prototype = new A;
改为执行此操作( 旧浏览器的Object.create
:
B.prototype = Object.create(A.prototype);
对于构造函数
,如果没有任何内容会破坏你不这样做,但如果你不这样做:
As for constructor
, nothing will break if you don't do this, but if you don't:
A = function() {};
var a = new A();
console.log(a.constructor); // A
B = function() {};
var b = new B();
console.log(b.constructor); // A (!)
...设置构造函数
原型的属性回到实际的构造函数允许你这样做:
...setting the constructor
property of the prototype back to the actual constructor function allows you to do this:
B.prototype.constructor = B;
var b = new B();
console.log(b.constructor); // B
这篇关于原型继承的构造函数赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!