class 中的构造方法未被调用

Constructor method in class not being called

我想创建一个 class Pixel 来存储给定像素的位置和颜色。

到目前为止,这是我的代码:

<canvas id="kartina" width="500" height="500"></canvas>
<input type="text" id="textField" size="80">

<script>
//pass in coordinates and Canvas context
function Pixel(x,y,ctx){

    //assign coordinate properties
    this.x=x;
    this.y=y;

    //get an array with the color data for the pixel
    this.pixelData=function(){
        return ctx.getImageData(x,y,1,1).data;
    };

    //assign color properties
    this.r=this.pixelData[0];
    this.g=this.pixelData[1];
    this.b=this.pixelData[2];

    //define toString method
    this.toString=function(){
                    var pixelToString=  "x: "+this.x+
                                        ", y: "+this.y+
                                        ", R: "+this.r+
                                        ", G: "+this.g+
                                        ", B: "+this.b;
                    return pixelToString;
    };
}

//test the class
var canvas=document.getElementById("kartina");
var ctx=canvas.getContext("2d");
var pixel=new Pixel(100,100,ctx);
textField.value=pixel.toString();
</script>

toString() 的输出是:

x: 100, y: 100, R: undefined, G: undefined, B: undefined

所以我知道坐标属性赋值正确,但是在new Pixel()构造实例时pixelData初始化函数没有被执行。我想让对象的构造函数调用这个初始化函数;我认为这是做到这一点的方法。我如何在这里设置构造函数?

由于 pixelData 是一个 函数 ,您需要 调用 它以获得您想要的结果:

//assign color properties
this.r=this.pixelData()[0];
this.g=this.pixelData()[1];
this.b=this.pixelData()[2];

或者更好:

var pData = this.pixelData();

this.r=pData[0];
this.g=pData[1];
this.b=pData[2];

您引用的 this.pixelData() 函数就好像它是一个使用 [] 方括号的数组。

函数根本不会被调用,因为您将其视为数组而不是调用函数,然后将结果视为数组。

改变这个:

this.r=this.pixelData[0];
this.g=this.pixelData[1];
this.b=this.pixelData[2];

为此:

this.r=this.pixelData()[0];
this.g=this.pixelData()[1];
this.b=this.pixelData()[2];

或者为了避免调用它三次:

//assign color properties
var pixelData = this.pixelData()
this.r = pixelData[0];
this.g = pixelData[1];
this.b = pixelData[2];