How to automatically apply argument to class constructor?

java constructor
javascript class constructor
constructors | c++
default constructor
default constructor in java
constructor javascript
constructor c#
constructor python

I have an es6 class User and a global function map() given below:

class  User {
  constructor(public name: string) {}
}

const map = <T, R>(project: (value: T) => R) => {}

Instead of writing the following:

map((value) => new User(value))

I want to (somehow) write something like:

map(new User)

I am not sure if this is possible or not.

You can create a static function in your class that takes the value param and returns a new User:

class User {
  static createUser(value) {
    return new User(value)
  }
}

And then use:

map(User.createUser)

Providing Constructors for Your Classes (The Java™ Tutorials , A class contains constructors that are invoked to create objects from the class The compiler automatically provides a no-argument, default constructor for any  Constructors. A constructor in C++ is a special method that is automatically called when an object of a class is created. To create a constructor, use the same name as the class, followed by parentheses ():

You can't do it directly. If you control the target function (ie it's not the stock map function) you can have it take a constructor instead of the function:

class User { constructor(private id: number) { }}
function map<TIn, T>(value: TIn, ctor: new (a: TIn) => T): T{
    return new ctor(value)
}
map(10, User)

Another more flexible solution is to use a helper function that transform the constructor into the desired function, although it's not much shorter then the original version:

class User { constructor(private id: number) { }}
function ctor<TIn, T>(ctor: new (a: TIn) => T): (value: TIn) => T{
    return value => new ctor(value)
}
[10, 11].map(ctor(User));

constructor, The constructor method is a special method for creating and initializing an object created within a class. Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator. Because this type of expression is an initialization, not an assignment, the assignment operator function, if one exists, is not called.

You could add a check with new.target if the function is called without new and call then function with new.

function Person(name) {
    if (!new.target) return new Person(...arguments);
    this.name = name;
}

var names = ['Jane', 'Dan', 'Grace', 'Paul'],
    instances = names.map(Person);

console.log(instances);

8.5, A constructor is a special kind of class member function that is automatically called (described in lesson 7.7 -- Default arguments) apply to constructors too. Constructors (C# Programming Guide) 05/05/2017; 2 minutes to read +7; In this article. Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible

The pattern you are describing is called a scope-safe constructor. It can be implemented by overloading a constructor so it works with and without the new keyword.

interface User {
  name: string;
}

interface UserConstructor {
  new (name: string): User;
  (name: string): User;
}

The same trick is used for global objects like Array or Date.

We need to recognize whether the new keyword was used:

const User = function (this: User | void, name: string): User {
  if (!(this instanceof User)) {
    return new User(name);
  }

  this.name = name;
  return this;
} as UserConstructor;

Your class has just become new-agnostic.

console.log(
  new User('Bob'),
  User('Alice'),
);

Which enabled us to write:

['Alice', 'Bob'].map(User); // $ExpectType User[]

java for complete beginners - class constructor, You don't need to make any special calls to a constructor method - they happen automatically when you create a new object. Constructor methods take the same​  If your class is a base class, the default constructor is empty: constructor() {} If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(args) { super(args); } That enables code like this to work:

This is a well known "problem" in the oop vs fp debate in JS - class constructors vs function constructors

since es6 classes need the new operator, it is impossible to write something like map(new User)

you need a wrapper around the class constructor that creates instances via a function call. IMO, @baboo's approach is way to go

class MyClass {
  // ...

  static create(...args) {
    return new MyClass(...args)
  }
}
const a = new MyClass('hello', [])
const b = MyClass.create('world', 123])

you can read more about the problems of new here.

also, checkout daggy - Library for creating tagged constructors

Generate a constructor quick action, Place your cursor in any empty line in a class: Pick the members you want to include as constructor parameters. check the Add null checks checkbox to automatically generate null checks for your constructor parameters. Constructors for struct types resemble class constructors, but structs cannot contain an explicit parameterless constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to the default value. However, this parameterless constructor is only invoked if the struct is instantiated with new.

Instance Constructors, To initialize a static class, or static variables in a non-static class, you of an automatically generated constructor is provided in Example 2. Constructor Overloading Example. Here we are creating two objects of class StudentData. One is with default constructor and another one using parameterized constructor. Both the constructors have different initialization code, similarly you can create any number of constructors with different-2 initialization codes for different-2 purposes.

4 Fun and Useful Things to Know about Scala's apply() functions, In fact, a built-in Scala macro has automatically generated an apply method to match our case class fields. The constructor still exists, and can  By default, the default constructor (a constructor without arguments) is invoked when we create an object. If we specify any arguments along with object creation, then the corresponding (argumented) constructor will be executed. Objects as arguments to a constructor: We can pass an object also as an argument to the constructor.

The Little Book on CoffeeScript, class Animal constructor: (name) -> @name = name By prefixing argument's with @ , CoffeeScript will automatically set the arguments as instance are extended, we can shortcut the process of applying both static and instance properties:. The name of the constructor should be the same as that of class. A Java constructor must not have a return type. If a class doesn't have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values.

Comments
  • new calls the class. in the second one, you get the same instance for every call.
  • How can I otherwise pass the constructor?
  • Possible duplicate of Passing a constructor to Array.map?
  • @MateuszWitkowski not exact duplicate, because in that question Date object has static constructor function as I understand and in my case it is different. I want to understand how new User will work without passing argument
  • All that to save twelve characters?
  • To allow for subclassing, I'd recommend to do return new this(value); though - and then you'd have to User.createUser.bind(User)
  • Thanks, that looks great, but for now I am trying to understand how the class constructor is going to work
  • Good point to support subclassing. Binding context to functions is slow though. A good compromise would be to override the function in the subclass
  • Yes I can actually control the map by writing my own high-order map function. I will try your version
  • Could this work for es6 classes as well ? (If I convert Person to a class I get Class constructor cannot be called without the new keyword at runtime)
  • no, because you would need a static constructor, which does not work.