diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
| commit | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (patch) | |
| tree | d4a40e13ceeb9f85479605110a76e7a4d5f3b56b /files/bg/web/javascript/reference/classes | |
| parent | 33058f2b292b3a581333bdfb21b8f671898c5060 (diff) | |
| download | translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.gz translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.bz2 translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.zip | |
initial commit
Diffstat (limited to 'files/bg/web/javascript/reference/classes')
4 files changed, 808 insertions, 0 deletions
diff --git a/files/bg/web/javascript/reference/classes/constructor/index.html b/files/bg/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..4d3971672e --- /dev/null +++ b/files/bg/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,130 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - Класове + - Конструктор +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>Методът <code>constructor</code> е специален метод за създаване и инициализиране на обект , <span lang="bg">създаден в рамките </span>класът (<code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class</a></code><span lang="bg">).</span></p> + +<div>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</div> + +<p class="hidden"><span lang="bg">Източникът на този интерактивен пример се съхранява в хранилище на GitHub. Ако искате да допринесете за проекта за интерактивни примери, моля клонирайте </span> <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> <span lang="bg"> и ни изпратете заявка за изтегляне.</span></p> + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox">constructor([<em>arguments</em>]) { ... }</pre> + +<h2 id="Описание">Описание</h2> + +<p>Може да има само един специален метод с име "constructor" в даден клас (class). <span lang="bg">Ако има повече от </span>един метод с името <code>constructor</code> в класът си , ще се появи грешка {{jsxref("SyntaxError")}}.</p> + +<p>Конструктора (<code>constructor</code>) може да използва ключовата дума <code>super</code> за да извика конструктора на родителския клас.</p> + +<p>Ако не посочите метода конструктор, ще се използва конструктор по подразбиране</p> + +<h2 id="Примери">Примери</h2> + +<h3 id="Използване_на_метода_constructor">Използване на метода <code>constructor</code></h3> + +<p>Този примерен код е взет от <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">демо на живо</a>).</p> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // Here, it calls the parent class' constructor with lengths + // provided for the Polygon's width and height + super(length, length); + // Note: In derived classes, super() must be called before you + // can use 'this'. Leaving this out will cause a reference error. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="Друг_пример">Друг пример</h3> + +<p>Разгледайте този код :</p> + +<pre class="brush: js">class Polygon { + constructor() { + this.name = "Polygon"; + } +} + +class Square extends Polygon { + constructor() { + super(); + } +} + +class Rectangle {} + +Object.setPrototypeOf(Square.prototype, Rectangle.prototype); + +console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false +console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true + +let newInstance = new Square(); +console.log(newInstance.name); //Polygon</pre> + +<p>Тук прототипа на класът <strong>Square</strong> се променя, но все пак конструктора на предишния базов клас <strong>Polygon </strong>се извиква, когато се създава нова инстанция(екземлпяр) от класът <strong>Square</strong>. Това е така , защото в класът <strong>Squre </strong>използваме ключовата дума <code>super</code>, извиквайки конструктора на родителският клас <strong>Polygon </strong>.</p> + +<h3 id="Конструктор_по_подразбиране">Конструктор по подразбиране</h3> + +<p>Както е посочено,ако не посочите метод конструктор, ще се използва конструктор по подразбиране . За базовите класове , конструктора по подразбиране е :</p> + +<pre class="brush: js">constructor() {} +</pre> + +<p>За производни класове, конструктора по подразбиране е :</p> + +<pre class="brush: js">constructor(...args) { + super(...args); +}</pre> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_с_браузъра">Съвместимост с браузъра</h2> + + + +<p>{{Compat("javascript.classes.constructor")}}</p> + +<h2 id="Въжте_също">Въжте също</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">ключовата дума super()</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>класов</code> израз</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>деклариране на клас</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Класове</a></li> +</ul> diff --git a/files/bg/web/javascript/reference/classes/extends/index.html b/files/bg/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..940e815d6c --- /dev/null +++ b/files/bg/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,112 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +tags: + - JavaScript наследяване + - Класове + - наследяване +translation_of: Web/JavaScript/Reference/Classes/extends +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>Ключовата дума <strong><code>extends</code></strong> се използва в <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">декларацията на класове</a> или <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">класовите изрази</a> за създаване на клас, който е дете на друг клас.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}</div> + + + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox">class ChildClass extends ParentClass { ... }</pre> + +<h2 id="Описание">Описание</h2> + +<p>Ключовата дума <strong><code>extends</code></strong> може да бъде използвана като подклас на потребителски класове, както и за вградени обекти.</p> + +<p>Прототипът (<code>.prototype</code>) на разширението трябва да е {{jsxref("Object")}} или {{jsxref("null")}}.</p> + +<h2 id="Примери">Примери</h2> + +<h3 id="Използване_на_extends">Използване на <code>extends</code></h3> + +<p>Първият пример създава клас, наречен <code>Square</code> от клас, наречен <code>Polygon</code> (<code>Square</code> класът наследява клас <code>Polygon</code> ). Този пример е взет от това <a href="https://googlechrome.github.io/samples/classes-es6/index.html">демо на живо</a> <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(източник)</a>.</p> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // Here, it calls the parent class' constructor with lengths + // provided for the Polygon's width and height + super(length, length); + // Note: In derived classes, super() must be called before you + // can use 'this'. Leaving this out will cause a reference error. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } +}</pre> + +<h3 id="Използване_на_extends_с_вградени_обекти">Използване на <code>extends</code> с вградени обекти</h3> + +<p>Този пример разширява вграденият {{jsxref("Date")}} обект. Този пример е взет от това <a href="https://googlechrome.github.io/samples/classes-es6/index.html">демо на живо</a> <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(източник)</a>.</p> + +<pre class="brush: js">class myDate extends Date { + constructor() { + super(); + } + + getFormattedDate() { + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear(); + } +}</pre> + +<h3 id="Наследяване_на_null">Наследяване на <code>null</code></h3> + +<p>Наследяване от {{jsxref("null")}} работи както при нормалните класове, eс изключение на това , <span lang="bg">че обектът на прототипа не наследява от</span> {{jsxref("Object.prototype")}}.</p> + +<pre class="brush: js">class nullExtends extends null { + constructor() {} +} + +Object.getPrototypeOf(nullExtends); // Function.prototype +Object.getPrototypeOf(nullExtends.prototype) // null + +new nullExtends(); //ReferenceError: this is not defined +</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('ES2015', '#sec-class-definitions', 'extends')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_с_браузъра">Съвместимост с браузъра</h2> + + + +<p>{{Compat("javascript.classes.extends")}}</p> + +<h2 id="Вижте_още">Вижте още</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Класове</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">ключовата дума super</a></li> + <li><a href="https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420">Anurag Majumdar - Super & Extends in JavaScript</a></li> +</ul> diff --git a/files/bg/web/javascript/reference/classes/index.html b/files/bg/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..dc88fc8548 --- /dev/null +++ b/files/bg/web/javascript/reference/classes/index.html @@ -0,0 +1,431 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript 2015 + - Inheritance + - Intermediate + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax <em>does not</em> introduce a new object-oriented inheritance model to JavaScript.</p> + +<h2 id="Defining_classes">Defining classes</h2> + +<p>Classes are in fact "special <a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a>", and just as you can define <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a>, the class syntax has two components: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">class expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class declarations</a>.</p> + +<h3 id="Class_declarations">Class declarations</h3> + +<p>One way to define a class is using a <strong>class declaration</strong>. To declare a class, you use the <code>class</code> keyword with the name of the class ("Rectangle" here).</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<h4 id="Hoisting">Hoisting</h4> + +<p>An important difference between <strong>function declarations</strong> and <strong>class declarations</strong> is that function declarations are {{Glossary("Hoisting", "hoisted")}} and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a {{jsxref("ReferenceError")}}:</p> + +<pre class="brush: js example-bad">const p = new Rectangle(); // ReferenceError + +class Rectangle {} +</pre> + +<h3 id="Class_expressions">Class expressions</h3> + +<p>A <strong>class expression</strong> is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) {{jsxref("Function.name", "name")}} property, though).</p> + +<pre class="brush: js">// unnamed +let Rectangle = class { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +console.log(Rectangle.name); +// output: "Rectangle" + +// named +let Rectangle = class Rectangle2 { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +console.log(Rectangle.name); +// output: "Rectangle2" +</pre> + +<div class="note"> +<p><strong>Note:</strong> Class <strong>expressions</strong> are subject to the same hoisting restrictions as described in the {{anch("Class declarations")}} section.</p> +</div> + +<h2 id="Class_body_and_method_definitions">Class body and method definitions</h2> + +<p>The body of a class is the part that is in curly brackets <code>{}</code>. This is where you define class members, such as methods or constructor.</p> + +<h3 id="Strict_mode">Strict mode</h3> + +<p>The body of a class is executed in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.</p> + +<h3 id="Constructor">Constructor</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> method is a special method for creating and initializing an object created with a <code>class</code>. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a <code>constructor</code> method.</p> + +<p>A constructor can use the <code>super</code> keyword to call the constructor of the super class.</p> + +<h3 id="Prototype_methods">Prototype methods</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>.</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } + // Getter + get area() { + return this.calcArea(); + } + // Method + calcArea() { + return this.height * this.width; + } +} + +const square = new Rectangle(10, 10); + +console.log(square.area); // 100</pre> + +<h3 id="Static_methods">Static methods</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> keyword defines a static method for a class. Static methods are called without <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instantiating </a>their class and <strong>cannot </strong>be called through a class instance. Static methods are often used to create utility functions for an application.</p> + +<pre class="brush: js">class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + + static distance(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + + return Math.hypot(dx, dy); + } +} + +const p1 = new Point(5, 5); +const p2 = new Point(10, 10); + +console.log(Point.distance(p1, p2)); // 7.0710678118654755</pre> + +<h3 id="Boxing_with_prototype_and_static_methods">Boxing with prototype and static methods</h3> + +<p>When a static or prototype method is called without a value for <em>this</em>, the <em>this</em> value will be <code>undefined</code> inside the method. This behavior will be the same even if the <code>"use strict"</code> directive isn't present, because code within the <code>class</code> body's syntactic boundary is always executed in strict mode.</p> + +<pre class="brush: js">class Animal { + speak() { + return this; + } + static eat() { + return this; + } +} + +let obj = new Animal(); +obj.speak(); // Animal {} +let speak = obj.speak; +speak(); // undefined + +Animal.eat() // class Animal +let eat = Animal.eat; +eat(); // undefined</pre> + +<p>If the above is written using traditional function-based syntax, then autoboxing in method calls will happen in non–strict mode based on the initial <em>this</em> value. If the initial value is <code>undefined</code>, <em>this</em> will be set to the global object.</p> + +<p>Autoboxing will not happen in strict mode, the <em>this</em> value remains as passed.</p> + +<pre class="brush: js">function Animal() { } + +Animal.prototype.speak = function() { + return this; +} + +Animal.eat = function() { + return this; +} + +let obj = new Animal(); +let speak = obj.speak; +speak(); // global object + +let eat = Animal.eat; +eat(); // global object +</pre> + +<h3 id="Instance_properties">Instance properties</h3> + +<p>Instance properties must be defined inside of class methods:</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<p>Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration:</p> + +<pre class="brush: js">Rectangle.staticWidth = 20; +Rectangle.prototype.prototypeWidth = 25; +</pre> + +<h3 id="Field_declarations">Field declarations</h3> + +<div class="warning"> +<p>Public and private field declarations are an <a href="https://github.com/tc39/proposal-class-fields">experimental feature (stage 3)</a> proposed at <a href="https://tc39.github.io/beta/">TC39</a>, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like <a href="https://babeljs.io/">Babel</a>.</p> +</div> + +<h4 id="Public_field_declarations">Public field declarations</h4> + +<p>With the JavaScript field declaration syntax, the above example can be written as:</p> + +<pre class="brush: js">class Rectangle { + height = 0; + width; + constructor(height, width) { + this.height = height; + this.width = width; + } +} +</pre> + +<p>By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.</p> + +<p>As seen above, the fields can be declared with or without a default value.</p> + +<h4 id="Private_field_declarations">Private field declarations</h4> + +<p>Using private fields, the definition can be refined as below.</p> + +<pre class="brush: js">class Rectangle { + #height = 0; + #width; + constructor(height, width) { + this.#height = height; + this.#width = width; + } +} +</pre> + +<p>It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version.</p> + +<div class="note"> +<p>Private fields can only be declared up-front in a field declaration.</p> +</div> + +<p>Private fields cannot be created later through assigning to them, the way that normal properties can.</p> + +<p> </p> + +<h2 id="Sub_classing_with_extends">Sub classing with <code>extends</code></h2> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> keyword is used in <em>class declarations</em> or <em>class expressions</em> to create a class as a child of another class.</p> + +<pre class="brush: js">class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Dog extends Animal { + constructor(name) { + super(name); // call the super class constructor and pass in the name parameter + } + + speak() { + console.log(this.name + ' barks.'); + } +} + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>If there is a constructor present in the subclass, it needs to first call super() before using "this".</p> + +<p>One may also extend traditional function-based "classes":</p> + +<pre class="brush: js">function Animal (name) { + this.name = name; +} + +Animal.prototype.speak = function () { + console.log(this.name + ' makes a noise.'); +} + +class Dog extends Animal { + speak() { + console.log(this.name + ' barks.'); + } +} + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use {{jsxref("Object.setPrototypeOf()")}}:</p> + +<pre class="brush: js">const Animal = { + speak() { + console.log(this.name + ' makes a noise.'); + } +}; + +class Dog { + constructor(name) { + this.name = name; + } +} + +// If you do not do this you will get a TypeError when you invoke speak +Object.setPrototypeOf(Dog.prototype, Animal); + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie makes a noise. +</pre> + +<h2 id="Species">Species</h2> + +<p>You might want to return {{jsxref("Array")}} objects in your derived array class <code>MyArray</code>. The species pattern lets you override default constructors.</p> + +<p>For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent <code>Array</code> object, instead of the <code>MyArray</code> object. The {{jsxref("Symbol.species")}} symbol lets you do this:</p> + +<pre class="brush: js">class MyArray extends Array { + // Overwrite species to the parent Array constructor + static get [Symbol.species]() { return Array; } +} + +let a = new MyArray(1,2,3); +let mapped = a.map(x => x * x); + +console.log(mapped instanceof MyArray); // false +console.log(mapped instanceof Array); // true +</pre> + +<h2 id="Super_class_calls_with_super">Super class calls with <code>super</code></h2> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.</p> + +<pre class="brush: js">class Cat { + constructor(name) { + this.name = name; + } + + speak() { + console.log(`${this.name} makes a noise.`); + } +} + +class Lion extends Cat { + speak() { + super.speak(); + console.log(`${this.name} roars.`); + } +} + +let l = new Lion('Fuzzy'); +l.speak(); +// Fuzzy makes a noise. +// Fuzzy roars. +</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>Abstract subclasses or <em>mix-ins</em> are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.</p> + +<p>A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:</p> + +<pre class="brush: js">let calculatorMixin = Base => class extends Base { + calc() { } +}; + +let randomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>A class that uses these mix-ins can then be written like this:</p> + +<pre class="brush: js">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.classes")}}</p> + +<h2 id="Running_in_Scratchpad">Running in Scratchpad</h2> + +<p>A class can't be redefined. If you're playing with code in Scratchpad (Firefox menu Tools > Web Developer > Scratchpad) and you 'Run' a definition of a class with the same name twice, you'll get a confusing SyntaxError: redeclaration of let <class-name>.</p> + +<p>To re-run a definition, use Scratchpad's menu Execute > Reload and Run.<br> + Please vote for bug <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1428672">#1428672</a>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> + <li><a href="https://github.com/tc39/proposal-class-fields">Fields and public/private class properties proposal (stage 3)</a></li> +</ul> diff --git a/files/bg/web/javascript/reference/classes/static/index.html b/files/bg/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..971bf40345 --- /dev/null +++ b/files/bg/web/javascript/reference/classes/static/index.html @@ -0,0 +1,135 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +tags: + - Класове + - Статичен + - статичен метод +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><span class="seoSummary">Ключовата дума <code><strong>static</strong></code> дефинира статичен метод за клас. Static methods aren't called on instances of the class. Instead, they're called on the class itself.</span> <span lang="bg">Това често са помощни функции, като например функции за създаване или клониране на обекти.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/classes-static.html")}}</div> + + + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox">static <em>methodName</em>() { ... }</pre> + +<h2 id="Описание">Описание</h2> + +<p>Статичните методи се правят директно в класът и не могат да се извикват като инстанции на клас.</p> + +<h2 id="Извикване_на_статичен_метод">Извикване на статичен метод</h2> + +<h3 id="От_друг_статичен_метод">От друг статичен метод</h3> + +<p>За да извикате статичен метод в рамките на друг статичен метод от същия клас, може да използвате ключовата дума <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>.</p> + +<pre class="brush: js">class StaticMethodCall { + static staticMethod() { + return 'Static method has been called'; + } + static anotherStaticMethod() { + return this.staticMethod() + ' from another static method'; + } +} +StaticMethodCall.staticMethod(); +// 'Static method has been called' + +StaticMethodCall.anotherStaticMethod(); +// 'Static method has been called from another static method'</pre> + +<h3 id="От_конструктора_на_клас_и_други_методи">От конструктора на клас и други методи</h3> + +<p>Статичните методи не са пряко достъпни, когато се използва ключовата дума <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> от нестатични методи. Трябва да ги извикате, използвайки името на класа: <code>CLASSNAME.STATIC_METHOD_NAME()</code> или да извикате метода като собственост на <code>constructor</code>: <code>this.constructor.STATIC_METHOD_NAME()</code>.</p> + +<pre class="brush: js">class StaticMethodCall { + constructor() { + console.log(StaticMethodCall.staticMethod()); + // 'static method has been called.' + + console.log(this.constructor.staticMethod()); + // 'static method has been called.' + } + + static staticMethod() { + return 'static method has been called.'; + } +}</pre> + +<h2 id="Примери">Примери</h2> + +<p>Следният пример показва няколко неща:</p> + +<ol> + <li>Как статичните методи се изпълняват в класът.</li> + <li>Това , че клас със статичен член може да бъде под-класиран.</li> + <li>Как статичният метод може и не може да бъде извикан.</li> +</ol> + +<pre class="brush: js">class Triple { + static triple(n) { + if (n === undefined) { + n = 1; + } + return n * 3; + } +} + +class BiggerTriple extends Triple { + static triple(n) { + return super.triple(n) * super.triple(n); + } +} + +console.log(Triple.triple()); // 3 +console.log(Triple.triple(6)); // 18 + +var tp = new Triple(); + +console.log(BiggerTriple.triple(3)); +// 81 (not affected by parent's instantiation) + +console.log(tp.triple()); +// 'tp.triple is not a function'. +</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('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Съвместимост_с_браузера">Съвместимост с браузера</h2> + + + +<p>{{Compat("javascript.classes.static")}}</p> + +<h2 id="Вижте_още">Вижте още</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>класови</code> израз</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">декларация на <code>клас</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Класове</a></li> +</ul> |
