-1
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;
});

This is an alternate implementation of constructor instantiation from JavaScript: The Good Parts. My question is why is do we need var other = ... Can't we just return the variable that?

apjak
  • 101
  • 4
  • You might want to read up on what the `&&` and `||` operators do: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators – Qantas 94 Heavy Jul 17 '14 at 03:22
  • Thanks for the link. It did help, but it didn't answer my question. The variable 'that' references the newly created object. So why even bother checking what type 'other' is? Could you straight return 'that'? – apjak Jul 17 '14 at 03:27
  • 1
    I think you're mostly getting downvotes because the title is misleading. You might want to edit the title to specifically what you are asking – George Mauer Jul 17 '14 at 03:33

1 Answers1

1

Can't we just return the variable that?

No, because that's not what the new operator does:

If the constructor function doesn't explicitly return an object, the object [that inherits from the protype] is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

So, if the call to the constructor function returns an other that is an object, we need to return that.

Notice that the code even isn't correct, as returned functions should be considered as objects as well (but typeof doesn't yield "object" for them). You might check for that as well, or use the Object(other) === other trick. You also might want to have a look at some of the answers to Use of .apply() with 'new' operator. Is this possible?.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375