javascript - 如何在我的函数 xCoor 未定义的情况下修复此参考错误
问题描述
代码的目标是只允许通用形状的 x 和 y 坐标为正值。
x 和 y 都必须定义为私有成员,只能在检查值后设置,如果发送给设置器的值为负数,则坐标将设置为 0
最后,构造函数必须调用 setter 函数
class Shape {
//takes essential points (EP)
constructor (x, y){
xCoor(x);
yCoor(y);
}
set xCoor(x){
if (x < 0){
this.x = 0;
} else {
this.x = x;
}
}
get xCoor(){
return this.x;
}
set yCoor(y){
if (y < 0){
this.y = 0;
} else {
this.y = y;
}
}
get yCoor(){
return this.y;
}
showPoint(){
console.log('(x, y) ' + this.x + ',' + this.y);
}
}
//so what are the properties of a shape?
//if circle centre would be EP
//if rectangle the top left corner would be EP
let circle = new Shape(5,5);
console.log(circle);
circle.showPoint();
//the error message
/*
xCoor(x);
^
ReferenceError: xCoor is not defined
at new Shape (/Users/anthonybarros/Desktop/Tutorial 8/tutorial6.js:4:9)
at Object.<anonymous> (/Users/anthonybarros/Desktop/Tutorial 8/tutorial6.js:35:14)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
*/
解决方案
尽可能简单地尝试
class Shape {
constructor (x, y){
// xCoor(x);
// yCoor(y);
this.x = x < 0 ? 0 : x;
this.y = y < 0 ? 0 : y;
}
showPoint(){
console.log('(x, y) ' + this.x + ',' + this.y);
}
}
let circle1 = new Shape(5,5);
let circle2 = new Shape(-5,5);
let circle3 = new Shape(-5,0);
console.log(circle1);
console.log(circle2);
console.log(circle3);
推荐阅读
- python - 如何在 Python 的 HeatMap 中指定我自己的标准
- javascript - 使用 javascript jquery 3.5.1 获取所有表格元素的值,包括 td、textarea 或 innerHtml 值
- c - _flushall() 在清除缓冲区时不起作用
- powershell - 从此 sha-1 文件中获取 sha-256
- r - 计算 Tukey 中位数
- sql - 如何使用sql server中的group子句从每个组中获取最新记录
- python - UnboundLocalError:创建构造函数后在成员函数中赋值之前引用的局部变量“温度”?
- c++ - 计算线的终点不起作用
- python - Np 值错误:使用序列设置数组元素
- c# - 从 Python 进程获取实时输出时缺少异常