javascript - 为什么代码给我错误“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
解决方案
你写的对 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());
推荐阅读
- node.js - 来自 Blob NodeJS 的视频流
- python - 烧瓶会话不持久化数据
- python - Python pandas excel输出不是确定的形式
- python - 如何查看编译后的python的结果?
- freeswitch - freeswtich docker 容器连接
- angular - 我们如何在具有角度 2 的剑道网格中使用多选下拉菜单
- .htaccess - 在 htaccess RewriteEngine 中不适用于特定目录
- android - 如何在 CoordinatorLayout 上使用 BottomSheet 提升 RecyclerView
- python - 运行 python 脚本并将参数捕获到另一个 python 脚本中
- java - 如何有效地为 MT20x 消息制作 Wrapper