有两种方法可以在子进程中调用父构造函数。
var A = function A() {
this.x = 123;
};
var B = function B() {
// 1. call directly
A.call(this);
// 2. call from prototype
A.prototype.constructor.call(this);
};
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
有没有一种情况比另一种更安全/更好,或者它们总是等价的?
最佳答案
直接使用基础构造函数总是更好,原因如下:
- 速度更快。解释器不需要访问
prototype.constructor
。 - 它更安全。考虑下面的程序。
A
继承自C
,但我忘记将A.prototype.constructor
设置回A
。所以它现在指向 C
。如果我们使用第二种方法,这会导致构造函数 B
出现问题:
var C = function C() {
// some code
};
var A = function A() {
this.x = 123;
};
A.prototype = Object.create(C.prototype);
// I forgot to uncomment the next line:
// A.prototype.constructor = A;
var B = function B() {
// 1. call directly
A.call(this);
// 2. call from prototype
A.prototype.constructor.call(this); // A.prototype.constructor is C, not A
};
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
关于javascript - 调用基本构造函数 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13272038/