Reason
  • Документация
  • Попробовать
  • API
  • Сообщество
  • Блог
  • Languages iconРусский
    • 日本語
    • English
    • Deutsch
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Українська
    • 中文
    • 繁體中文
    • Помочь с переводом
  • GitHub

›Advanced Features

Введение

  • Что и зачем

Установка

  • Установка
  • Плагины для редакторов и IDE

Основы языка

  • Обзор
  • Let Bindings
  • Primitives
  • Basic Structures
  • Types
  • Records
  • Variants
  • Options and nullability
  • Functions
  • Recursion
  • Деструктуризация
  • Pattern Matching
  • Mutable Bindings
  • Loops
  • Modules

Advanced Features

  • JSX
  • External
  • Исключения
  • Объекты

JavaScript

  • Взаимодействие с JavaScript
  • Шпаргалка по синтаксису
  • Pipe First
  • Промис
  • Библиотеки
  • Конвертация из JS

Дополнительно

  • Часто задаваемые вопросы (FAQ)
  • Дополнительные инструменты
Translate

Объекты

Большую часть времени вы будете использовать записи для пар ключ-значение. Однако, в некоторых ситуациях вы возможно захотите использовать объекты. Они немного более гибкие, но приносят свои компромиссы.

Использование

Декларация типа

An object doesn't need a type declaration, though it can have one. It looks like a record, except with a .:

type tesla = {
  .
  color: string
};

The dot at the beginning indicates that this is a "closed" object type, which means that an object based on this type must have exactly this shape.

type car('a) = {
  ..
  color: string
} as 'a;

Two dots, also called an elision, indicate that this is an "open" object type, and therefore can also contain other values and methods. An open object is also polymorphic and therefore requires a parameter.

Создание

Simple

type tesla = {
  .
  color: string,
};

let obj: tesla = {
  val red = "Red";
  pub color = red;
};

Js.log(obj#color) /* "Red" */

Here we have a simple object with the method color and the property red. This method takes no arguments and returns the private property red. Because the method color is a public method we can access it using object notation. Remember, objects only export methods and all properties are private.

Advanced

type tesla = {.
  drive: int => int
};

let obj: tesla = {
  val hasEnvy = ref(false);
  pub drive = (speed) => {
    this#enableEnvy(true);
    speed
  };
  pri enableEnvy = (envy) => hasEnvy := envy
};

This object is of object type tesla and has a public method drive. It also contains a private method enableEnvy that is only accessible from within the object.

As you can see, a Reason object can also access this. JavaScript object's this behavior can be quirky; Reason this always points to the object itself correctly.

The following example shows an open object type which uses a type as parameter. The object type parameter is required to implement all the methods of the open object type.

type tesla('a) = {
  ..
  drive: int => int
} as 'a;

let obj: tesla({. drive: int => int, doYouWant: unit => bool}) = {
  val hasEnvy = ref(false);
  pub drive = (speed) => {
    this#enableEnvy(true);
    speed
  };
  pub doYouWant = () => hasEnvy^;
  pri enableEnvy = (envy) => hasEnvy := envy
};

You can use the above object like so:

obj#doYouWant();
← ИсключенияВзаимодействие с JavaScript →
  • Использование
    • Декларация типа
    • Создание
  • Simple
  • Advanced