首页 > 解决方案 > 为什么代码给我错误“SyntaxError: Unexpected token {”?

问题描述

执行以下代码时,出现错误:SyntaxError: Unexpected token {

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

标签: javascriptfunction

解决方案


你写的对 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());

如果您使用的是 normal 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());


推荐阅读