Почему код выдает ошибку «SyntaxError: Неожиданный токен {»? - PullRequest
0 голосов
/ 02 июля 2019

При выполнении приведенного ниже кода появляется сообщение об ошибке: SyntaxError: неожиданный токен {

const a = function(x,y){
  this.x = x;
  this.y = y;

  getX(){
    return this.x;
  }

  getY(){
    return this.y;
  }


};

const newA = new a( '1', '2' );

console.log( newA.getX() );
console.log( newA.getY() );

Ожидаемый результат: 1 2

Ответы [ 5 ]

3 голосов
/ 02 июля 2019

То, что вы написали, действительно для ES6 + class декларация :

class a {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  getX() {
    return this.x;
  }

  getY() {
    return this.y;
  }
};

const newA = new a('1', '2');

console.log(newA.getX());
console.log(newA.getY());

Если вы используете обычный function, вам нужно явно назначить свойства:

const a = function(x, y) {
  this.x = x;
  this.y = y;

  this.getX = function() {
    return this.x;
  }

  this.getY = function() {
    return this.y;
  }
};

const newA = new a('1', '2');

console.log(newA.getX());
console.log(newA.getY());

Или используйте прототип, поэтому каждый экземпляр a будет использовать одни и те же методы вместо создания одного набора на экземпляр :

const a = function(x, y) {
  this.x = x;
  this.y = y;
};

a.prototype.getX = function() {
  return this.x;
}

a.prototype.getY = function() {
  return this.y;
}


const newA = new a('1', '2');

console.log(newA.getX());
console.log(newA.getY());
1 голос
/ 02 июля 2019

Это не так, как классы работают в JavaScript. Есть два способа сделать OO в JavaScript:

Традиционный ОО на основе прототипа:

// Traditionally javascript does not have classes, but functions can
// behave as constructors if you give it a prototype:

function A (x, y) {
    this.x = x;
    this.y = y;
}

A.prototype.getX = function() {return this.x};
A.prototype.getY = function() {return this.y};

В качестве альтернативы вы можете использовать новый синтаксис class:

"Новые" классы ES6 (на самом деле сейчас они довольно старые)

class A {
    constructor (x,y) {
        this.x = x;
        this.y = y;
    }

    getX() { return this.x }

    getY() { return this.y }
}

Вы смешиваете элементы обоих синтаксисов, что, к сожалению, приводит к неверному синтаксису

1 голос
/ 02 июля 2019

Вы используете синтаксис класса внутри функции.

Вы можете создать функцию конструктора и добавить методы к a.prototype

function a(x, y) {
  this.x = x;
  this.y = y;
};

a.prototype.getX = function() {
  return this.x;
}

a.prototype.getY = function() {
  return this.y;
}
const newA = new a('1', '2');

console.log(newA.getX());
console.log(newA.getY());

Или создайте class следующим образом:

class a {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  
  getX() {
    return this.x;
  }

  getY() {
    return this.y;
  }
};

const newA = new a('1', '2');

console.log(newA.getX());
console.log(newA.getY());

Другой вариант - создать getter для X и Y:

class a {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  
  get X() {
    return this.x;
  }

  get Y() {
    return this.y;
  }
};

const newA = new a('1', '2');

console.log(newA.X);
console.log(newA.Y);
1 голос
/ 02 июля 2019

Функции должны быть назначены как свойства, ref :

const a = function(x, y) {
  this.x = x;
  this.y = y;

  this.getX = function() {
    return this.x;
  }

  this.getY = function() {
    return this.y;
  }


};

const newA = new a('1', '2');

console.log(newA.getX());
console.log(newA.getY());
0 голосов
/ 02 июля 2019

Синтаксис:

  getX(){
    return this.x;
  }

… предназначен для использования внутри литерала объекта или класса , а не выражения функции.

class A {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  
  getX() {
    return this.x;
  }

  getY() {
    return this.y;
  }
};

const newA = new A('1', '2');

console.log(newA.getX());
console.log(newA.getY());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...