Prototype and Classes

Minwoo Gwak·2023년 3월 16일
0

The prototype object contains all the methods and properties that instances of the class will inherit. When you create a new instance of a class using the new
keyword, JavaScript creates a new object that inherits from the prototype of the constructor function.

class Person {
    constructor(name, age, height, weight) {
        this.name = name;
        this.age = age;
        this.weight = weight;
        this.height = height;
    }

    info() {
        console.log(`${this.name} is ${this.age} years old.`);
        console.log(`Height: ${this.height}cm`)
        console.log(`Weight: ${this.weight}`);
    }
}

let jacob = new Person('Jacob', 23, 176, 68);

console.log(Person.prototype.constructor === Person); //True
console.log(Person.prototype === jacob.__proto__);    //True
console.log(Person.prototype.info === jacob.info);    //True

In the above example, Person is a class that defines a constructor function and a prototype object. The ‘constructor’ method sets the name, age, weight, height properties of a new instance of the class and the ‘info’ method logs an information by given information of the person.

profile
CS and Math student at the University of Illinois with a passion for web development and aspiring to become a frontend developer.

0개의 댓글