首页 > 解决方案 > 如何在我的函数 xCoor 未定义的情况下修复此参考错误

问题描述

  1. 代码的目标是只允许通用形状的 x 和 y 坐标为正值。

  2. x 和 y 都必须定义为私有成员,只能在检查值后设置,如果发送给设置器的值为负数,则坐标将设置为 0

  3. 最后,构造函数必须调用 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
*/

标签: javascriptclassgetter-setter

解决方案


尽可能简单地尝试

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);


推荐阅读