问题描述
使用纯JavaScript进行继承,这就是我通常所做的事情:
Using pure JavaScript to do inheritance, this is what I usually do:
function A() {}
A.prototype.run = function () {};
function B() {}
B.prototype = new A;
B.prototype.constructor = B;
由于没有参数传递给构造函数,新的A没有什么可抱怨的。现在,如果构造函数有参数传递,我还没有想出一个很好的继承方法。例如,
Since there is no arguments to pass into the constructor, new A has nothing to complain about. Now, I haven't figured out a good way to do inheritance if the constructor has arguments to pass. For example,
function A(x, y) {}
A.prototype.run = function () {};
function B(x, y) {}
B.prototype = new A;
B.prototype.constructor = B;
我可以传递一些任意值,如:
I could pass some arbitrary values like:
B.prototype = new A(null, null);
在某些情况下,我可能需要在A的构造函数中验证x和y。在某些极端在检查x或y时,我需要抛出错误。然后,B无法使用新A从A继承。
In some cases, I may need to validate x and y in the constructor of A. In some extreme cases, I need throw errors when checking x or y. Then, there is no way for B to inherit from A using new A.
有任何建议吗?
谢谢!
推荐答案
好吧,如果你想做 B.prototype
一个继承自 A.prototype
的对象,而不执行 A
构造函数,为避免所有可能的副作用,您可以使用虚拟构造函数来执行此操作,例如:
Well, if you want to make B.prototype
an object that inherits from A.prototype
, without executing the A
constructor, to avoid all possible side-effects, you could use a dummy constructor to do it, for example:
function tmp() {}
tmp.prototype = A.prototype;
B.prototype = new tmp();
B.prototype.constructor = B;
你可以创建一个函数来封装这个新对象的创建逻辑,例如:
You could create a function to encapsulate the logic of the creation of this new object, e.g.:
function inherit(o) {
function F() {}; // Dummy constructor
F.prototype = o;
return new F();
}
//...
B.prototype = inherit(A.prototype);
B.prototype.constructor = B;
如果您定位现代浏览器,则可以使用ECMAScript 5 Object.create
用于相同目的的方法,例如:
If you target modern browsers, you could use the ECMAScript 5 Object.create
method for the same purpose, e.g.:
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
//..
这篇关于JavaScript继承:当构造函数有参数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!