Create new object using person constructor javascript
Here is an example of creating a new object using a Person
constructor in JavaScript:
// Define the Person constructor
function Person(name, age) {
this.name = name;
this.age = age;
}
// Create a new Person object
const person1 = new Person("John Doe", 30);
// Access the properties of the new object
console.log(person1.name); // Output: "John Doe"
console.log(person1.age); // Output: 30
In this example, we define a Person
constructor that takes two arguments: name
and age
. The constructor sets the name
and age
properties of the new object using the this
keyword.
We then create a new Person
object using the new
keyword, passing in the arguments "John Doe"
and 30
. The new
keyword creates a new object and calls the Person
constructor, passing in the arguments.
Finally, we access the properties of the new object using dot notation (person1.name
and person1.age
). This outputs the values we set in the constructor.
You can also create multiple objects using the same constructor:
const person2 = new Person("Jane Smith", 25);
const person3 = new Person("Bob Johnson", 40);
console.log(person2.name); // Output: "Jane Smith"
console.log(person2.age); // Output: 25
console.log(person3.name); // Output: "Bob Johnson"
console.log(person3.age); // Output: 40