Javascript: What is the difference between a function and a class

With the release of ECMAScript 6 in June 2015, Javascript class syntax was introduced.

This syntax:

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

basically the same as:

function Polygon(width, height) {
    this.width = width;
    this.height = height;
}

So what is the advantage of using a class instead of a traditional function? And in what state should I use the class instead of the function?

+7
source share
2 answers

Class Function - , " ", . JS JavaScript, AST, , ClassDeclaration ClassExpression - node AST :

https://github.com/estree/estree/blob/master/es2015.md#classes

, ES6 AST:

  • ClassBody
  • MethodDefinition
  • ClassDeclaration
  • ClassExpression
  • MetaProperty

AST , , , , - JavaScript.

, . ,

class notWorking {
  return 1;  // <-- creates a parser error
};

, , ClassBody ClassDeclaration, ClassExpression, expexts, MethodDefinitions.

, . :

function myClass() {
    var privateVar;
}

:

class myClass {
    var privateVar; // ERROR: should be a method
}

, . , .

:

https://github.com/zenparsing/es-private-fields

,

class myClass {
   #privateVar; // maybe this works in the future?
}

, ES6, , :

JavaScript ES6

var property = Symbol(); // private property workaround example
class Something {
    constructor(){
        this[property] = "test";
    }
}

, . - 1 - :

, . ,

;

function foo1() {} // can be used before declaration
class  foo2{}      // new foo2(); works only after this declaration

, exressions, , :

var myClass = class foobar {};

1

  • exression/declaration -
  • - , . ""
  • super, . , super (x, y);, , super.foobar(), . , .
  • static, , ClassName.FunctionName() -syntax.
  • extends, Dog extends Animal
  • Declaration -prefix, "ok" "m" : class m {ok() {}}. m {function ok() {}}

, , , .

ES6 , , , , .

EDIT: , ES6 : - . , ES7 , . , , , .

1 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

+15

class , javascript function. function class, , -, this.something = ... var something = ... ( , , /), , - .

0

Source: https://habr.com/ru/post/1690783/


All Articles