---
title: Определение методов
slug: Web/JavaScript/Reference/Functions/Method_definitions
translation_of: Web/JavaScript/Reference/Functions/Method_definitions
original_slug: Web/JavaScript/Reference/Functions/Определение_методов
---
<div>{{JsSidebar("Functions")}}</div>

<p>Начиная с ECMAScript 6, существует короткий синтаксис для определения методов в инициализаторе объекта. По сути, это сокращение для функции, которая назначена имени метода.</p>

<h2 id="Синтаксис">Синтаксис</h2>

<pre class="syntaxbox">var obj = {
  <var>property</var>([<var>parameters</var>]) {},
  get <var>property</var>() {},
  set <var>property</var>(<var>value</var>) {},
  * <var>generator</var>() {}
};
</pre>

<h2 id="Описание">Описание</h2>

<p>Короткий синтаксис похожий на синтаксис <a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a>'ов и <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a>'ов представленных в ECMAScript 5.</p>

<p>Следующий код:</p>

<pre class="brush: js">var obj = {
  foo: function() {},
  bar: function() {}
};</pre>

<p>Вы теперь можете сократить до:</p>

<pre class="brush: js">var obj = {
  foo() {},
  bar() {}
};</pre>

<h3 id="Сокращение_методов-генераторов">Сокращение методов-генераторов</h3>

<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">Методы-генераторы</a> также могут быть определены используя короткий синтаксис. Обратите внимание, что звездочка (*) в коротком синтаксисе должна быть перед именем свойства генератора. То есть, <code>* g(){}</code> будет работать, а <code>g *(){}</code> не будет.</p>

<pre class="brush: js;highlight[12]">// Используя свойство с именем (pre-ES6)
var obj2 = {
  g: function*() {
    var index = 0;
    while(true)
      yield index++;
  }
};

// Тот же объект используя короткий синтаксис
var obj2 = {
  * g() {
    var index = 0;
    while(true)
      yield index++;
  }
};

var it = obj2.g();
console.log(it.next().value); // 0
console.log(it.next().value); // 1</pre>

<h3 id="Определения_методов_(ES6)_не_могут_быть_конструкторами">Определения методов (ES6) не могут быть конструкторами</h3>

<p>Все определения методов кроме методов-генераторов не могут быть конструкторами и будут выбрасывать {{jsxref("TypeError")}} если вы попытаетесь создать их экземпляр.</p>

<pre class="brush: js">var obj = {
  method() {},
};
new obj.method; // TypeError: obj.method is not a constructor

var obj = {
  * g() {}
};
new obj.g; // Генератор
</pre>

<h2 id="Примеры">Примеры</h2>

<h3 id="Простой_тестовый_пример">Простой тестовый пример</h3>

<pre class="brush: js;highlight[3]">var obj = {
  a : "foo",
  b(){ return this.a; }
};
console.log(obj.b()); // "foo"
</pre>

<h3 id="Вычисляемые_имена_свойств">Вычисляемые имена свойств</h3>

<p>Короткий синтаксис также поддерживает вычисляемые имена свойств.</p>

<pre class="brush: js;highlight[4]">var bar = {
  foo0 : function (){return 0;},
  foo1(){return 1;},
  ["foo" + 2](){return 2;},
};

console.log(bar.foo0()); // 0
console.log(bar.foo1()); // 1
console.log(bar.foo2()); // 2</pre>

<h2 id="Спецификации">Спецификации</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Спецификация</th>
   <th scope="col">Статус</th>
   <th scope="col">Комментарий</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Изначальное определение.</td>
  </tr>
 </tbody>
</table>

<h2 id="Совместимость_с_браузерами">Совместимость с браузерами</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Method definition shorthand</td>
   <td>{{CompatChrome("39")}}</td>
   <td>{{CompatGeckoDesktop("34")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatOpera("26")}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Method definition shorthand</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile("34")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="sect1"> </h2>

<h2 id="SpiderMonkey-specific_notes">SpiderMonkey-specific notes</h2>

<ul>
 <li>Prior to SpiderMonkey 38 {{geckoRelease(38)}},  "<code>get</code>" and "<code>set</code>" were invalid names for generator methods. This has been fixed in {{bug(1073809)}}.</li>
 <li>Prior to SpiderMonkey 41 {{geckoRelease(41)}}, curly braces were not required in method definitions. They are required from now on to conform to the ES6 specification and will throw a {{jsxref("SyntaxError")}} in this and later versions ({{bug(1150855)}}).
  <pre class="brush: js example-bad">var o = {x() 12}; // SyntaxError</pre>
 </li>
 <li>The restriction that only generator methods are constructors has been implemented in SpiderMonkey 41 {{geckoRelease(41)}}. See also {{bug(1059908)}} and {{bug(1166950)}}.</li>
</ul>

<h2 id="Смотрите_также">Смотрите также</h2>

<ul>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></code></li>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></code></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li>
</ul>