Jodes Jodes - 1 year ago 89
Javascript Question

Purpose of passing a single argument to Object ()?

In an answer to this previous question, what is the purpose of passing an argument to

s constructor, using it as a function, as per the following code?

function makeFoo(a, b) {
var foo = Object.create(Foo.prototype);
var result = Foo.apply(foo, arguments);
return Object(result) === result ? result : foo;

Answer Source

The Object constructor returns its parameter if it's already an object. What your code is doing therefore is checking to see if the result value is an object.

In the context of that function from the other question, the goal is to deal with the fact that the "Foo" constructor might try to return a non-object (like a string or something) when invoked other than via new. When you call a constructor with new, then any non-object explicit return value is ignored, and the return value will be the constructed object.

So that last line of "makeFoo" checks to see whether the returned value is already an object. If it is, then the Object constructor will return the reference without creating a new object, so it will be === to the parameter ("result"). If it's not ===, then that means the constructor did something weird, and so the constructed "foo" instance will be returned instead.

And note that the other question described this as a "hack".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download