Js

Class (JavaScript)

A class in JavaScript is a blueprint for creating objects, defined with the class keyword.

This page covers Class in JavaScript. For a language-agnostic introduction, see Class.

Defining a Class#

class Player {
}

By convention, class names use PascalCase: Player, OddsAndEvens, RockPaperScissors.

Adding a Constructor#

The constructor method runs automatically when an object is created. Use it to set the initial state.

class Player {
    constructor(name) {
        this.name = name;
    }
}

this.name = name stores the value on the object. this refers to the current instance.

Constructor (JavaScript)

In JavaScript, the constructor is a special method inside a class that runs automatically when you create an object with new.

This page covers Constructor in JavaScript. For a language-agnostic introduction, see Constructor.

Defining a Constructor#

The constructor method is always named constructor. It receives arguments and uses this to store them on the object.

class Player {
    constructor(name) {
        this.name = name;
    }
}

Creating an Object#

Pass arguments to new when creating the object. JavaScript calls constructor automatically.

Method (JavaScript)

A method in JavaScript is a function defined inside a class body.

This page covers Method in JavaScript. For a language-agnostic introduction, see Method.

Defining a Method#

Methods in a JavaScript class are written without the function keyword — just the name, parentheses, and body.

class Player {
    greet() {
        console.log("Hello!");
    }
}

By convention, method names use camelCase: greet, play, getScore.

Return Values#

Use return to send a value back. A method without a return statement returns undefined.