The new keyword is used in JavaScript to create an object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things:
new constructor[([arguments])]
- Creates a new object
- Sets the prototype of this object to the constructor function’s prototype property
- Binds the
this
keyword to the newly created object and executes the constructor function - Returns the newly created object
New keyword in JavaScript
Simple example code can create an instance of a user-defined object type or of one of the built-in object types that have a constructor function.
<!DOCTYPE html>
<html>
<body>
<script>
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
console.log(car1);
</script>
</body>
</html>
Output:
Javascript creates prototype objects
function MyFunc() {
this.name = "Hello";
}
MyFunc.prototype.book = "Javascript";
let obj1 = new MyFunc();
console.log(obj1.name);
console.log(obj1.book);
Output: Hello
Javascript
Comment if you have any doubts or suggestions on this JS keyword topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version