Classes and Objects

Classes and Objects

> LeekScript Tutorial

Welcome to the documentation on object-oriented programming (OOP) which consists of creating classes and objects to organize your code. This feature was added from LeekScript 2.

Objects

Objects are values grouping several values each associated with a name. These values are called properties or fields.

Creating an object

To create an object, we use the following syntax:

In this example, the object object has two properties, name and age.

To create an empty object:

Access to a property

The dot . allows access to a property of an object:

An alternative syntax exists: object["prop"], allowing to use a string value to access a property:

Modifying a property

Once accessed, a property can be modified like a normal variable:

Object Comparison

The == and === operators only compare if the object is the same. They return false even if the two objects have the same properties:

List of properties

Classes

A class is a model for creating objects.

Defining a class

We define a Weapon class with the 4 fields named this way:

Creating an object with a class

The new is actually optional, a class is similar to a function and can be called directly to create an object:

You can retrieve the class of an object using .class:

instanceof

The instanceof keyword is used to check if an object is an instance of a class:

Builders

A constructor is a function defined in a class allowing to create an object from a list of parameters. We define a constructor like this:

Using a constructor:

Methods

A method is a function defined in a class and usable on an object of this class. We define a method like this:

We use a method with the syntax:

The object["member"] syntax also works:

It is not advisable to use it, the risk of making a mistake is quite strong.

Overload

It is possible to overload methods by simply changing the number of parameters

You can then use the method with one or two parameters of your choice:

Legacy

The notion of inheritance makes it possible to create a hierarchy of classes. We use this syntax with the extends keyword. We are trying to declare a "base" class from which other classes can be built. Classes that inherit receive all the members (variables) and methods (functions) of the base class, and can redefine them, or add new ones.

```leekscript class Item { id name cost damage }