为什么 goog.inherits
来自 Google Closure Library 看起来像这样:
goog.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};
而不是
goog.inherits = function(childCtor, parentCtor) {
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new parentCtor();
childCtor.prototype.constructor = childCtor;
};
tempCtor
有什么好处?
最佳答案
如果 parentCtor
有一些初始化代码,并且在最坏的情况下需要一些参数,那么代码可能会意外失败。这就是他们创建虚拟函数并从中继承的原因。
关于javascript - 为什么在进行 Javascript 继承时要创建一个临时构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23239285/