К основному содержанию
скилл CX Codex

prototype-pattern — скилл для Claude Code: что делает и как установить

Обучает ИИ-агента паттерну Prototype для JavaScript и TypeScript. Помогает экономить память через цепочку прототипов и общие методы объектов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PatternsDev/skills --skill prototype-pattern -a claude-code
Открыть на GitHub

Что делает prototype-pattern

Скилл задаёт модели правила работы с прототипным наследованием в файлах **/*.js и **/*.ts. Он предписывает выносить общие методы в прототип вместо создания дубликатов функций внутри каждого нового экземпляра.

В инструкциях описаны два подхода. Первый опирается на ES6-классы, в которых методы добавляются в прототип автоматически. Второй использует Object.create() для прямого связывания прототипов без вызова конструктора. Модель также учится связывать цепочку через extends и super.

Скилл рассчитан строго на код JavaScript и TypeScript. Если проект не создаёт множество однотипных сущностей, пользы от выноса методов не будет.

Какие задачи решает

  • вынести повторяющиеся методы объектов в прототип для экономии памяти
  • связать цепочку прототипов через Object.create() без конструктора
  • настроить наследование классов через extends и super
  • предотвратить дублирование функций при создании множества инстансов

Примеры запросов агенту

  • Отрефактори создание пользователей через Object.create, чтобы они разделяли общие методы
  • Покажи, как перенести метод расчёта в прототип класса вместо создания функции в конструкторе
  • Проверь файл models.ts на избыточное дублирование методов в инстансах

Как установить prototype-pattern

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill prototype-pattern -a claude-code

2Вручную: положить файлы

~/.claude/skills/prototype-pattern/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/prototype-pattern/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о prototype-pattern

Как установить prototype-pattern в Claude Code?

Выполните команду npx skills add PatternsDev/skills --skill prototype-pattern -a claude-code. Файл скилла сохранится по пути ~/.claude/skills/prototype-pattern/SKILL.md.

Что делает скилл prototype-pattern?

Он объясняет агенту правила прототипного наследования в JavaScript и подсказывает, как делить методы между экземплярами через прототипы.

Для каких файлов действует этот скилл?

Инструкции скилла применяются только к файлам по маскам **/*.js и **/*.ts.

Исходный текст

SKILL.md · MIT
---
name: prototype-pattern
description: Teaches the prototype pattern for property sharing via the prototype chain. Use when creating many objects of the same type that should share methods or properties efficiently.
paths:
  - "**/*.js"
  - "**/*.ts"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "module-pattern"
  - "singleton-pattern"
---

# Prototype Pattern

The prototype pattern is a useful way to share properties among many objects of the same type. The prototype is an object that's native to JavaScript, and can be accessed by objects through the prototype chain.

In our applications, we often have to create many objects of the same type. A useful way of doing this is by creating multiple instances of an ES6 class.

## When to Use

- Use this when many objects need access to the same methods without duplicating them
- This is helpful for understanding JavaScript's inheritance model and ES6 classes

## Instructions

- Use ES6 classes to automatically add methods to the prototype
- Use `Object.create()` to create objects with a specific prototype
- Leverage the prototype chain for inheritance (`extends` keyword in ES6 classes)
- Understand that properties on the prototype are shared and not duplicated per instance

## Details

Let's say we want to create many dogs! In our example, dogs can't do that much: they simply have a name, and they can bark!

```js
class Dog {
  constructor(name) {
    this.name = name;
  }

  bark() {
    return `Woof!`;
  }
}

const dog1 = new Dog("Daisy");
const dog2 = new Dog("Max");
const dog3 = new Dog("Spot");
```

Notice here how the `constructor` contains a `name` property, and the class itself contains a `bark` property. When using ES6 classes, all properties that are defined on the class itself, `bark` in this case, are automatically added to the `prototype`.

We can see the `prototype` directly through accessing the `prototype` property on a constructor, or through the `__proto__` property on any _instance_.

```js
console.log(Dog.prototype);
// constructor: ƒ Dog(name, breed) bark: ƒ bark()

console.log(dog1.__proto__);
// constructor: ƒ Dog(name, breed) bark: ƒ bark()
```

The value of `__proto__` on any instance of the constructor, is a direct reference to the constructor's prototype! Whenever we try to access a property on an object that doesn't exist on the object directly, JavaScript will _go down the prototype chain_ to see if the property is available within the prototype chain.

The prototype pattern is very powerful when working with objects that should have access to the same properties. Instead of creating a duplicate of the property each time, we can simply add the property to the prototype, since all instances have access to the prototype object.

Since all instances have access to the prototype, it's easy to add properties to the prototype even after creating the instances.

Say that our dogs shouldn't only be able to bark, but they should also be able to play! We can make this possible by adding a `play` property to the prototype.

The term **prototype chain** indicates that there could be more than one step. Indeed! So far, we've only seen how we can access properties that are directly available on the first object that `__proto__` has a reference to. However, prototypes themselves also have a `__proto__` object!

Let's create another type of dog, a super dog! This dog should inherit everything from a normal `Dog`, but it should also be able to fly. We can create a super dog by extending the `Dog` class and adding a `fly` method.

```js
class SuperDog extends Dog {
  constructor(name) {
    super(name);
  }

  fly() {
    return "Flying!";
  }
}
```

We have access to the `bark` method, as we extended the `Dog` class. The value of `__proto__` on the prototype of `SuperDog` points to the `Dog.prototype` object!

It gets clear why it's called a prototype _chain_: when we try to access a property that's not directly available on the object, JavaScript recursively walks down all the objects that `__proto__` points to, until it finds the property!

### `Object.create`

The `Object.create` method lets us create a new object, to which we can explicitly pass the value of its prototype.

```js
const dog = {
  bark() {
    return `Woof!`;
  },
};

const pet1 = Object.create(dog);
```

Although `pet1` itself doesn't have any properties, it does have access to properties on its prototype chain! Since we passed the `dog` object as `pet1`'s prototype, we can access the `bark` property.

`Object.create` is a simple way to let objects directly inherit properties from other objects, by specifying the newly created object's prototype. The new object can access the new properties by walking down the prototype chain.


The prototype pattern allows us to easily let objects access and inherit properties from other objects. Since the prototype chain allows us to access properties that aren't directly defined on the object itself, we can avoid duplication of methods and properties, thus reducing the amount of memory used.

## Source

- [patterns.dev/vanilla/prototype-pattern](https://patterns.dev/vanilla/prototype-pattern)

### References

- [Object.create - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
- [Prototype - ECMA](https://www.ecma-international.org/ecma-262/5.1/#sec-4.3.5)

© patterns.dev · MIT · PatternsDev/skills

Похожие скиллы

Все скиллы по теме «Языки программирования» →
migrate-to-shoehorn Matt Pocock Переводит type assertions с as в тестах на функции из @total-typescript/shoehorn. Нужен для частичных объектов и намеренно неверных данных в проверках. 475 388установок write-swift emilkowalski Скилл помогает писать, проверять и переносить код на Swift с учётом модели языка. Подойдёт, когда нужно разобраться с конкурентностью, ошибкой или циклом удержания объектов. CX Codex +1 119 300установок megacave JuliusBrussee Переводит ответы ассистента на классический китайский язык (вэньянь) для экономии места на экране. Активируется командами /megacave или /caveman wenyan. CX Codex +1 25 400установок find-docs upstash Тянет актуальную документацию, справочники API и примеры кода для любой библиотеки через Context7 CLI. Пригодится, когда агент отвечает по устаревшим данным обучения. CX Codex +1 9 400установок typescript-advanced-types Seth Hobson Помогает агенту писать сложную типизацию TypeScript: generics, conditional types и преобразования типов. Нужен для библиотек, API-клиентов и строгих конфигураций. CX Codex 92 169установок smart-explore thedotmack Структурно ищет функции и классы через tree-sitter. Пригодится, когда нужно разобраться в кодовой базе без чтения всех файлов. CX Codex +1 7 300установок

Из того же набора46

observer-pattern Скилл объясняет паттерн наблюдателя и подсказывает агенту, как строить слабосвязанную подписку на события в JS и TS. CX Codex +1 638установок factory-pattern Учит агента создавать объекты через фабричные функции. Пригодится, когда логика создания объектов зависит от конфигурации или окружения. CX Codex +1 634установок module-pattern Обучает ИИ-агента делить JavaScript и TypeScript на изолированные модули через ES2015. Помогает скрыть внутренние переменные и настроить чистый экспорт. CX Codex +1 631установок islands-architecture Скилл объясняет паттерн островной архитектуры и частичной гидратации. Пригодится, когда страница почти вся статичная, а интерактив нужен точечно. CX Codex +1 624установок provider-pattern Учит агента выносить общие данные в React Context и раздавать их через Provider, когда пропсы приходится тянуть через десяток компонентов. CX Codex +1 620установок mixin-pattern Обучает агента паттерну примесей в JavaScript и TypeScript для добавления общего поведения классам без наследования через прототипы. CX Codex +1 616установок proxy-pattern Скилл объясняет паттерн Proxy в JavaScript: перехват чтения и записи свойств объекта, валидация и логирование. Пригодится, когда агенту нужно править такой код. CX Codex +1 612установок mediator-pattern Скилл объясняет паттерн «посредник»: компоненты общаются через одну точку, а не напрямую. Пригодится, когда связей между объектами стало слишком много. CX Codex +1 608установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой