首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何解决在构造函数中使用该构造函数作为输入时的非法构造函数错误?

如何解决在构造函数中使用该构造函数作为输入时的非法构造函数错误?
EN

Stack Overflow用户
提问于 2022-05-26 13:36:24
回答 1查看 56关注 0票数 0

我有以下错误:

代码语言:javascript
运行
复制
TypeError: Illegal constructor
    at new Car (car.js:15:23)
    at main.js:7:13

汽车构造师在这里排队

代码语言:javascript
运行
复制
constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;    
        this.controls = new Controls();
        this.sensor = new Sensor(this);
    }

this.sensor = new Sensor(this);上抛出错误

创建汽车对象的方式如下:

const car = new Car(2, 100, 30, 50);

知道我为什么会犯这个错误吗?我想我应该能够使用this作为参数,所以不确定为什么会抛出错误。

这是我使用的类传感器:

代码语言:javascript
运行
复制
class Sensor{
    constructor(car){
        this.car = car;
        this.rayCount = 3;
        this.rayLength = 100;
        this.raySpread = Math.PI / 4;
        this.rays = [];
    }

    update(){
        this.rays = [];
        for(let i = 0; i < this.rayCount; i++){
            const rayAngle = lerp(
                this.raySpread / 2, 
                - this.raySpread / 2, 
                i / (this.rayCount - 1)
            );

            const start = {x : this.car.x, y: this.car.y};
            const end = {
                x: this.car.x - Math.sin(rayAngle) * this.rayLength,
                y: this.car.y - Math.cos(rayAngle) * this.rayLength
            };

            this.rays.push([start, end]);
        }
    }

    draw(context) {
        for(let i = 0; i < this.rayCount; i++){
            context.beginPath();
            context.lineWidth = 2;
            context.strokeStyle = "yellow";
            context.moveTo(
                this.rays[i][0].x,
                this.rays[i][0].y
            );
            context.lineTo(
                this.rays[i][1].x, 
                this
            );
            context.stroke();
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-09-24 05:35:00

从此更改" this“的行。

代码语言:javascript
运行
复制
constructor(x, y, width, height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

    this.sensor = new Sensor(this);
    this.controls = new Controls
to this
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;

        this.sensor = new Sensor(this);
        this.controls = new Controls

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72392720

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档