JavaScript Object Constructor

작성자

카테고리:

← 피드로
DEV Community · karthika jasinska · 2026-07-05 개발(SW)
Cover image for JavaScript Object Constructor

karthika jasinska

Object Constructor Functions
Sometimes we need to create many objects of the same type.

To create an object type we use an object constructor function.

It is considered good practice to name constructor functions with an upper-case first letter.

Example:

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather);
Output:
Person {firstName: 'John', lastName: 'Doe', age: 50, eyeColor: 'blue'}

Enter fullscreen mode Exit fullscreen mode

Adding a Property to a Constructor:
To add a new property, you must add it to the constructor function prototype:

Person.prototype.nationality = "Tamil";
console.log(myFather.nationality);
output:
Tamil

Enter fullscreen mode Exit fullscreen mode

Adding a Method to an Object
Adding a method to a created object is easy,The new method will be added to myMother. Not to any other Person Objects

// Constructor function for Person Objects
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create 2 Person objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

// Add a Name Method
myMother.changeName = function (name) {
  this.lastName = name;
}

// Change Name
myMother.changeName("Deo");
console.log(myMother.lastName)

Output:
Deo

Enter fullscreen mode Exit fullscreen mode

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다