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/ca/web/javascript/referencia/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/ca/web/javascript/referencia/classes')
3 files changed, 627 insertions, 0 deletions
diff --git a/files/ca/web/javascript/referencia/classes/constructor/index.html b/files/ca/web/javascript/referencia/classes/constructor/index.html new file mode 100644 index 0000000000..a0bd6b966f --- /dev/null +++ b/files/ca/web/javascript/referencia/classes/constructor/index.html @@ -0,0 +1,129 @@ +--- +title: constructor +slug: Web/JavaScript/Referencia/Classes/constructor +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +<div>{{jsSidebar("Classes")}}</div> + +<h2 id="Resum">Resum</h2> + +<p>El mètode <code>constructor</code> és un mètode especial per crear i inicialitzar un objecte creat amb una <code>class</code>.</p> + +<h2 id="Sintaxi">Sintaxi</h2> + +<pre class="syntaxbox">constructor([arguments]) { ... }</pre> + +<h2 id="Descripció">Descripció</h2> + +<p>Només hi pot haver un mètode especial am el nom "constructor" en una classe. Es llançarà un {{jsxref("SyntaxError")}}, si la classe conté més d'un cas d'un mètode <code>constructor</code>.</p> + +<p>Un constructor pot utilitzar la paraula clau <code>super</code> per cridar el constructor de la classe pare.</p> + +<h2 id="Exemples">Exemples</h2> + +<p>Aquest fragment de codi es pren de <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">mostra de classes</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">demostració en viu</a>).</p> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // Aquí es crida el constructor del pare de la classe amb les longituts + // proveïdes per l'amplada i l'alçada del polígon + super(length, length); + // Nota: En classes derivades, s'ha de cridar super() abans + // d'utilitzar 'this'. Obviar això causarà un error de referència. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h2 id="Especificacions">Especificacions</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificació</th> + <th scope="col">Estat</th> + <th scope="col">Comentaris</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definició inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilitat_amb_navegadors">Compatibilitat amb navegadors</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suport bàsic</td> + <td>{{CompatChrome(42.0)}}</td> + <td> + <p>Disponible només al canal Nightly (desde febrer del 2015)</p> + </td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome per Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suport bàsic</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + <td>Disponible només al canal Nightly (desde febrer del 2015)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notes_específiques_per_Firefox">Notes específiques per Firefox</h3> + +<ul> + <li>Els constructors estàndards encara no s'han implementat ({{bug(1105463)}})</li> +</ul> + +<h2 id="Vegeu_també">Vegeu també</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">expressió </a><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> </a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">declaració </a><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> </a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/ca/web/javascript/referencia/classes/index.html b/files/ca/web/javascript/referencia/classes/index.html new file mode 100644 index 0000000000..23daf7e1ff --- /dev/null +++ b/files/ca/web/javascript/referencia/classes/index.html @@ -0,0 +1,382 @@ +--- +title: Classes +slug: Web/JavaScript/Referencia/Classes +tags: + - Classes + - ECMAScript 2015 + - Experimental + - Expérimental(2) + - JavaScript + - NeedsContent + - NeedsTranslation + - Reference + - Référence(2) + - 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 <strong>does not</strong> 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">var 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) <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name">.name</a> property, though)</p> + +<pre class="brush: js">// unnamed +var Rectangle = class { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +console.log(Rectangle.name); +// output: "Rectangle" + +// named +var Rectangle = class Rectangle2 { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +console.log(Rectangle.name); +// output: "Rectangle2" +</pre> + +<p><strong>Note:</strong> Class <strong>expressions</strong> also suffer from the same hoisting issues mentioned for Class <strong>declarations</strong>.</p> + +<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 bodies of <em>class declarations</em> and <em>class expressions</em> are executed in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.</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 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.498039);">undefined</span></font> 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> syntax 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 inital 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> + +<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 { + speak() { + console.log(this.name + ' barks.'); + } +} + +var d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>If there is a constructor present in 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.'); + } +} + +var 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">var 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); + +var 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; } +} + +var a = new MyArray(1,2,3); +var 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.</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.'); + } +} + +var 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">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var 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/ca/web/javascript/referencia/classes/static/index.html b/files/ca/web/javascript/referencia/classes/static/index.html new file mode 100644 index 0000000000..3255dc1552 --- /dev/null +++ b/files/ca/web/javascript/referencia/classes/static/index.html @@ -0,0 +1,116 @@ +--- +title: static +slug: Web/JavaScript/Referencia/Classes/static +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>La paraula clau <strong>static</strong> defineix un mètode estàtic per a una classe.</p> + +<h2 id="Sintaxi">Sintaxi</h2> + +<pre class="syntaxbox">static methodName() { ... }</pre> + +<h2 id="Descripció">Descripció</h2> + +<p><u>Els mètodes estàtics es criden sense realitzar una instantània de la seva classe o instantiating their class nor are they callable when the class is instantiated</u>. Els mètodes estàtics s'utilitzen sovint per crear funcions d'utilitat per una aplicació.</p> + +<h2 id="Exemples">Exemples</h2> + +<p>L'exemple següent mostra diverses coses. Mostra com un mètode estàtic és implementat en una classe i que una classe amb un membre estàtic pot tenir subclasses. Finalment, mostra com es pot i com no es pot cridar un mètode estàtic.</p> + +<pre class="brush: js">class Tripple { + static tripple(n) { + n = n | 1; + return n * 3; + } +} + +class BiggerTripple extends Tripple { + static tripple(n) { + return super.tripple(n) * super.tripple(n); + } +} + +console.log(Tripple.tripple()); +console.log(Tripple.tripple(6)); +console.log(BiggerTripple.tripple(3)); +var tp = new Tripple(); +console.log(tp.tripple()); //Logs 'tp.tripple is not a function'.</pre> + +<h2 id="Especificacions">Especificacions</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificació</th> + <th scope="col">Estat</th> + <th scope="col">Comentaris</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definició inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilitat_amb_navegadors">Compatibilitat amb navegadors</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suport bàsic</td> + <td>{{CompatChrome(42.0)}}</td> + <td>Disponible només en el canal Nightly (desde febrer del 2015)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome per Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suport bàsic</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + <td>Disponible només en el canal Nightly (desde febrer del 2015)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Vegeu_també">Vegeu també</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">expressió </a><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> </a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">declaració </a><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> </a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> |