new

Summary

Instantiates a class.

Syntax

new class([ argument1 [, argument2 ... [, [ ... ] argumentN ]]])

Parameters

class
The class to instantiate.
argumentN
Any legal expression to supply as an argument to the class constructor.

Description

For JS++ Code

For JS++ classes, declared with the class keyword, the new keyword will instantiate a class.

1
2
3
class Dog {}
 
Dog dog = new Dog();

Constructor Overloading

The class constructor will be invoked during instantiation. If no constructors were specified, the default constructor will be invoked, which simply returns a new instance of the class. If the class being instantiated has overloaded constructors, the compiler will match the argument types to the parameter types of the defined constructor overloads available for the class. If no matching constructor is found, the compiler will raise an error.

1
2
3
4
5
6
7
8
9
10
11
12
class Dog
{
    private string name;
 
    public Dog() {}
    public Dog(string name) {
        this.name = name;
    }
}
 
Dog dog = new Dog(); // Instantiate a new 'Dog' without providing a name
Dog fido = new Dog("Fido"); // Instantiate a new 'Dog' named "Fido"

Inheritance

While new will return an object having the type of the class being instantiated, it will be compatible with all types the class inherits from, including other classes and interfaces. For example:

1
2
3
4
5
6
interface IAnimal {}
class Dog : IAnimal {}
class Cat : IAnimal {}
 
IAnimal pet = new Dog(); // Instantiate a 'Dog' and assign it to variable 'pet' with type 'IAnimal'
pet = new Cat(); // Change the 'pet' to a 'Cat' instance

For JavaScript Code

For JavaScript code with the external type, new creates a new object using a constructor function. The constructor follows the standard rules and behavior of functions, and may perform actions in addition to assigning properties to the new object. The this operator is used within the function to assign properties:

1
2
3
4
5
6
7
function Planet(string n, float m, float r) {
    this.name = n;
    this.mass = m;
    this.radius = r;
}
 
var mars = new Planet("Mars", 0.108, 0.53);

See Also

Share

HTML | BBCode | Direct Link