From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../referencia/classes/constructor/index.html | 129 +++++++ .../web/javascript/referencia/classes/index.html | 382 +++++++++++++++++++++ .../referencia/classes/static/index.html | 116 +++++++ 3 files changed, 627 insertions(+) create mode 100644 files/ca/web/javascript/referencia/classes/constructor/index.html create mode 100644 files/ca/web/javascript/referencia/classes/index.html create mode 100644 files/ca/web/javascript/referencia/classes/static/index.html (limited to 'files/ca/web/javascript/referencia/classes') 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 +--- +
{{jsSidebar("Classes")}}
+ +

Resum

+ +

El mètode constructor és un mètode especial per crear i inicialitzar un objecte creat amb una class.

+ +

Sintaxi

+ +
constructor([arguments]) { ... }
+ +

Descripció

+ +

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 constructor.

+ +

Un constructor pot utilitzar la paraula clau super per cridar el constructor de la classe pare.

+ +

Exemples

+ +

Aquest fragment de codi es pren de mostra de classes (demostració en viu).

+ +
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;
+  }
+}
+ +

Especificacions

+ + + + + + + + + + + + + + +
EspecificacióEstatComentaris
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES6')}}Definició inicial.
+ +

Compatibilitat amb navegadors

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatChrome(42.0)}} +

Disponible només al canal Nightly  (desde febrer del 2015)

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatUnknown}}{{CompatChrome(42.0)}}Disponible només al canal Nightly  (desde febrer del 2015){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Notes específiques per Firefox

+ + + +

Vegeu també

+ + 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 +--- +
{{JsSidebar("Classes")}}
+ +

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

+ +

Defining classes

+ +

Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

+ +

Class declarations

+ +

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Rectangle" here).

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

An important difference between function declarations and class declarations 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")}}:

+ +
var p = new Rectangle(); // ReferenceError
+
+class Rectangle {}
+
+ +

Class expressions

+ +

A class expression 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) .name property, though)

+ +
// 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"
+
+ +

Note: Class expressions also suffer from the same hoisting issues mentioned for Class declarations.

+ +

Class body and method definitions

+ +

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor.

+ +

Strict mode

+ +

The bodies of class declarations and class expressions are executed in strict mode i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.

+ +

Constructor

+ +

The constructor method is a special method for creating and initializing an object created with a class. 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 constructor method.

+ +

A constructor can use the super keyword to call the constructor of the super class.

+ +

Prototype methods

+ +

See also method definitions.

+ +
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
+ +

Static methods

+ +

The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

+ +
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
+ +

Boxing with prototype and static methods

+ +

When a static or prototype method is called without a value for this, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class syntax is always executed in strict mode.

+ +
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
+ +

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 this value. If the inital value is undefined, this will be set to the global object.

+ +

Autoboxing will not happen in strict mode, the this value remains as passed.

+ +
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
+
+ +

Instance properties

+ +

Instance properties must be defined inside of class methods:

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration:

+ +
Rectangle.staticWidth = 20;
+Rectangle.prototype.prototypeWidth = 25;
+
+ +

+ +

Sub classing with extends

+ +

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

+ +
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.
+
+ +

If there is a constructor present in subclass, it needs to first call super() before using "this".

+ +

One may also extend traditional function-based "classes":

+ +
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.
+
+ +

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()")}}:

+ +
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.
+
+ +

Species

+ +

You might want to return {{jsxref("Array")}} objects in your derived array class MyArray. The species pattern lets you override default constructors.

+ +

For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The {{jsxref("Symbol.species")}} symbol lets you do this:

+ +
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
+
+ +

Super class calls with super

+ +

The super keyword is used to call corresponding methods of super class.

+ +
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.
+
+
+ +

Mix-ins

+ +

Abstract subclasses or mix-ins 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.

+ +

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

+ +
var calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+var randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}}
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}}
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.classes")}}

+ +

Running in Scratchpad

+ +

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>.

+ +

To re-run a definition, use Scratchpad's menu Execute > Reload and Run.
+ Please vote for bug #1428672.

+ +

See also

+ + 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 +--- +
{{jsSidebar("Classes")}}
+ +

La paraula clau static defineix un mètode estàtic per a una classe.

+ +

Sintaxi

+ +
static methodName() { ... }
+ +

Descripció

+ +

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. Els mètodes estàtics s'utilitzen sovint per crear funcions d'utilitat per una aplicació.

+ +

Exemples

+ +

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.

+ +
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'.
+ +

Especificacions

+ + + + + + + + + + + + + + +
EspecificacióEstatComentaris
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Definició inicial.
+ +

Compatibilitat amb navegadors

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatChrome(42.0)}}Disponible només en el canal Nightly  (desde febrer del 2015){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatUnknown}}{{CompatChrome(42.0)}}Disponible només en el canal Nightly  (desde febrer del 2015){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Vegeu també

+ + -- cgit v1.2.3-54-g00ecf