I am unsure the exact question.

`new` will allocate an object with a prototype for sure, but it is never
guaranteed to return that object even with classes.

```js
let a = {};
class Foo {
  constructor() {
    return a;
  }
}
const g = new Foo();
console.log(new Foo() === g);
```

If the question is "How can an external observer know if a constructor
returns `this` vs some other object?" the answer is, you cannot.

On Thu, Jan 19, 2017 at 9:03 PM, Scott Sauyet <sc...@sauyet.com> wrote:

> Michael Haufe <t...@thenewobjective.com> wrote:
> > The question came up recently on CLJS [1] on how to determine if an
> object
> > is safe to call as a Constructor.
>
> The original question was a response to
>
>
> || You cannot determine whether a function can be called as a constructor
> || unless you try it.
>
>
> that asked the more specific question
>
>
> | What would count as positive evidence that a function can actually be
> | called *reasonably* as a constructor function?
>
>
> I was wondering if there was any way to distinguish a function like this
>
> ```js
>     var fn = (function() {
>       var g = {};
>       return function() {return g;};
>     }());
> ```
>
> which will pass all the proposed tests here, but still does not
> actually serve as a constructor function as is made clear by
>
> ```js
>     // no errors here
>     var obj1 = new fn();
>     var obj2 = new fn();
>
>     obj1.foo = 'bar'
>     obj2; //=> {foo: 'bar'}
> ```
>
> Without defining constructor functions explicitly, one would certainly
> hope that they would create new objects on each invocation, that there
> is some sort of difference between constructor functions and factory
> functions.
>
> I wasn't really expecting there to be a positive answer.  But I was
> curious and raised the issue.  (For all I know, this is wandering into
> issues similar to the Halting Problem.)
>
> But does anyone have a suggestion for a test that would reliably tell
> whether a function can serve as a true constructor in this manner?
>
>   -- Scott
> _______________________________________________
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to