[英]What's the advantage of goog.inherits' use of a temporary constructor?
From Google's Closure library: 来自Google的Closure库:
goog.inherits = function(childCtor, parentCtor) {
/** @constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
};
What is the advantage to the temporary constructor that is created? 创建的临时构造函数有什么优势?
Is there a reason the code doesn't just look like this: 是否有一个原因代码不是这样的:
goog.inherits = function(childCtor, parentCtor) {
/** @constructor */
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new parentCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
};
The first snippet is not calling the parentCtor
- it is not instantiating an object with invoking the constructor on it, it just inherits from the parentCtor.prototype
- actually it's a workaround for Object.create
(very old browsers lack support of it). 第一个片段没有调用
parentCtor
- 它不是通过调用构造函数来实例化一个对象,它只是从parentCtor.prototype
继承 - 实际上它是Object.create
的一种解决方法(很老的浏览器缺乏对它的支持)。 See also Understanding Crockford's Object.create shim on how the tempCtor
works and What is the reason [not] to use the 'new' keyword here? 又见了解克罗克福德的垫片的Object.create对如何
tempCtor
工作以及是什么原因[不]在这里使用了“新”的关键字? on the undesirability of calling the parent. 关于呼叫父母的不受欢迎程度。
You can only use "new parentCtor" if: (a) it will succeed without any parameters (b) you want the values set on the "this" value in parentCtor on your prototype. 如果出现以下情况,您只能使用“new parentCtor”:(a)它将在没有任何参数的情况下成功(b)您希望在原型上的parentCtor中的“this”值上设置值。
You see people do this in simple cases: 你看到人们在简单的情况下这样做:
var C = function() {};
C.prototype = new P();
But you can see how this can fail if P is: 但是你可以看到如果P是这样的话会失败:
var P = function(a) {a.x()} // throws if "a" is undefined.
The tempCtor avoids this. tempCtor避免这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.