Javascript 什么';这是谷歌的优势。继承';使用临时构造函数?

Javascript 什么';这是谷歌的优势。继承';使用临时构造函数?,javascript,google-closure,Javascript,Google Closure,从谷歌的关闭库: goog.inherits = function(childCtor, parentCtor) { /** @constructor */ function tempCtor() {}; tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @ove

从谷歌的关闭库:

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;
};
创建的临时构造函数的优势是什么

代码不是这样的原因是什么:

goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new parentCtor();
  /** @override */
  childCtor.prototype.constructor = childCtor;
};

第一个片段不是调用
parentCtor
——它不是通过调用对象上的构造函数来实例化对象,它只是继承了
parentCtor.prototype
——实际上这是一个解决方法(非常旧的浏览器不支持它)。另请参见
temptor
的工作原理以及调用父级的不可取之处。

只有在以下情况下,才能使用“new parentCtor”: (a) 它将在没有任何参数的情况下成功 (b) 您希望在原型的parentCtor中的“this”值上设置值

你可以看到人们在简单的情况下这样做:

var C = function() {};
C.prototype = new P();
但是你可以看到,如果p是:

var P = function(a) {a.x()}  // throws if "a" is undefined.

tempCtor避免了这种情况。

哦,好的-函数(childCtor,parentCtor){childCtor.prototype=Object.create(parentCtor);}做这个把戏吗?
对象。创建(parentCtor.prototype)
,但是是的。