new
Creates an instance of an object from a constructor function or class.
Syntax
new Constructor(args)
Returns
object — A newly created object linked to `Constructor.prototype`, unless the
constructor returns its own object.
Throws
TypeError— The operand is not a constructor.
Examples
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);
console.log(p.x, p.y);
Output
1 2
function Animal(name) {
this.name = name;
}
const a = new Animal("cat");
console.log(a.name);
Output
cat
const d = new Date(0);
console.log(d.getTime());
Output
0
Notes
- `new` creates a fresh object, binds it to `this`, links its prototype,
and returns it unless the constructor returns another object.
- `new.target` inside a function tells whether it was called with `new`.
- Arrow functions cannot be constructed with `new`.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |