The new Keyword
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 5 of 56.
The new keyword in JavaScript is used to create instances of constructor functions, which act as templates for creating objects.
Create a constructor function for a Person:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return "Hello, my name is " + this.name;
};
}Use the new keyword to create an instance:
const john = new Person("John", 30);After executing the above code, john is an object with properties and a method:
john.nameis "John"john.ageis 30john.greet()returns "Hello, my name is John"
Without the new keyword, this would refer to the global object (or undefined in strict mode), not the new instance.
Challenge
Create a Car Object and Print Its Description
You're given a constructor function that creates car objects. Your task is to:
- Create a new car object using the
newkeyword, pass "Honda" as the name and 2018 as the year - Call the
getDescriptionmethod on your car object - Print the result to the console
Cheat sheet
The new keyword creates instances of constructor functions, which act as templates for objects.
Define a constructor function:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return "Hello, my name is " + this.name;
};
}Create an instance using new:
const john = new Person("John", 30);Access properties and methods:
john.name // "John"
john.age // 30
john.greet() // "Hello, my name is John"Without new, this refers to the global object (or undefined in strict mode) instead of the new instance.
Try it yourself
function Car(name, year) {
this.name = name;
this.year = year;
this.getDescription = function() {
return "This is a " + this.name + " from " + this.year;
};
}
// TODO: Create a new car object using the new keyword, pass "Honda" as the name and 2018 as the year
// TODO: Call the getDescription method on your car object and print the result to the console
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge