在执行以下代码时,出现错误: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
答案 0 :(得分:3)
您写的内容对ES6 + class
declaration有效:
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 :(得分:1)
需要将功能分配为属性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());
答案 2 :(得分:1)
您正在函数内部使用类语法。
您可以创建一个构造函数并将方法添加到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());
另一种选择是为X
和Y
创建一个getter
:
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);
答案 3 :(得分:1)
这不是javascript中类的工作方式。有两种方法可以在javascript中进行OO:
// 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
语法:
class A {
constructor (x,y) {
this.x = x;
this.y = y;
}
getX() { return this.x }
getY() { return this.y }
}
您正在混合使用这两种语法的元素-不幸的是,这会导致语法无效
答案 4 :(得分:0)
语法:
getX(){
return this.x;
}
…是在对象文字或 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());