Javascript 为什么代码会给我错误“;SyntaxError:意外标记{";?

Javascript 为什么代码会给我错误“;SyntaxError:意外标记{";?,javascript,function,Javascript,Function,执行以下代码时,出现错误: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() ); 预期

执行以下代码时,出现错误: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需要将函数指定为属性:

<代码>常量a=功能(x,y){ 这个.x=x; 这个。y=y; this.getX=函数(){ 归还这个.x; } this.getY=函数(){ 把这个还给我; } }; const newA=新a('1','2'); log(newA.getX()); console.log(newA.getY());语法:

  getX(){
    return this.x;
  }
…用于对象文字或类内部,而不是函数表达式

A类{
构造函数(x,y){
这个.x=x;
这个。y=y;
}
getX(){
归还这个.x;
}
格蒂(){
把这个还给我;
}
};
const newA=新A('1','2');
log(newA.getX());

console.log(newA.getY());
您编写的内容对ES6+有效:

a类{
构造函数(x,y){
这个.x=x;
这个。y=y;
}
getX(){
归还这个.x;
}
格蒂(){
把这个还给我;
}
};
const newA=新a('1','2');
log(newA.getX());

console.log(newA.getY());
您正在函数中使用类语法

您可以创建构造函数并将方法添加到
a.prototype

函数a(x,y){
这个.x=x;
这个。y=y;
};
a、 prototype.getX=函数(){
归还这个.x;
}
a、 prototype.getY=函数(){
把这个还给我;
}
const newA=新a('1','2');
log(newA.getX());

console.log(newA.getY());
类在javascript中不是这样工作的。在javascript中有两种实现OO的方法:

传统的、基于原型的OO: 或者,您可以使用新的
class
语法:

“新”ES6课程(实际上现在已经很旧了)

您正在混合这两种语法的元素-这不幸导致无效语法

getX(){
-这里没有
函数
关键字,因此
getX()
只能表示函数调用。a
{
直接在函数调用之后在语法上是没有意义的。@04FS或者,OP意味着使用
语法,但这不在
块中
// 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 A {
    constructor (x,y) {
        this.x = x;
        this.y = y;
    }

    getX() { return this.x }

    getY() { return this.y }
}