basarat
basarat

Reputation: 276313

The new Operator

Is it possible to write a javascript function that follows this (valid) typescript interface:

interface Foo{
    // constructor: 
    new (): string; 
}

i.e. Something that when called with a new operator returns a string. e.g. the following will not work.

function foo(){
    return "something";
} 
var x = new foo(); 
// x is now foo (and not string) whether you like it or not :) 

Upvotes: 3

Views: 394

Answers (2)

apsillers
apsillers

Reputation: 116020

ECMAScript 5's Section 13.2.2 (on the [[Construct]] internal property) has this to say about the return value of a constructor:

1) Let obj be a newly created native ECMAScript object.

...

8) Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.

9) If Type(result) is Object then return result.

10) Return obj.

Thus, the return value of a constructor can only be an object. A string primitive like "foo" has a Type result of String rather than Object. This means that step 9 is false, so step 10 returns the constructed object, instead of the return value of the constructor function.

Instead, you must return an object (new String("foo")), as detailed in RobH's answer.

Upvotes: 2

RobH
RobH

Reputation: 3612

You should be able to do:

function foo(){
    return new String("something");
} 
var x = new foo(); 

console.log(x);

You can return any object, but literals don't work. See here: What values can a constructor return to avoid returning this?

Upvotes: 5

Related Questions