在Javascript中查看构造函数调用的另一种方法

时间:2014-07-17 03:11:49

标签: javascript object constructor

Function.prototype.new = function ( ) {
   // Create a new object that inherits from the
   // constructor's prototype.
   var that = Object.create(this.prototype);
   // Invoke the constructor, binding –this- to
   // the new object.
   var other = this.apply(that, arguments);
   // If its return value isn't an object,
   // substitute the new object.
   return (typeof other === 'object' && other) || that;
});

这是JavaScript的构造函数实例化的替代实现:Good Parts。 我的问题是为什么我们需要var other = ... 我们不能只返回变量吗?

1 个答案:

答案 0 :(得分:1)

  

我们不能只返回那个变量吗?

不,因为那不是new operator的作用:

  

如果构造函数没有显式返回一个对象,那么   而是使用了[继承自protype]的对象。 (一般   构造函数不返回值,但是如果它们可以选择这样做   他们想要覆盖正常的对象创建过程。)

因此,如果对构造函数的调用返回一个作为对象的other,我们需要返回它。

请注意,代码甚至不正确,因为返回的函数也应该被视为对象(但typeof不会为它们产生"object")。您也可以检查一下,或使用Object(other) === other trick。您还可以查看Use of .apply() with 'new' operator. Is this possible?的一些答案。