Javascript类属性总是未定义的

Javascript class properties always undefined

本文关键字:未定义 属性 Javascript      更新时间:2023-09-26

在我下面的类定义中,我的宽度,高度,列等在调用我的drawElipse方法时总是未定义的。

但是在我的页面中我设置了所有的属性。

$(document).ready(function() {
    var element = $('#positioning_canvas');
    element.click(scientificBox.click);
    scientificBox.columns = 9;
    scientificBox.rows = 9;
    scientificBox.canvas = element.get(0);
    etc.

如何解决这个问题?

var scientificBox = new function () {
var aliquotHeight;
var aliquotWidth;
this.width = 500;
this.height = 500;
this.columns = 9;
this.rows = 9;
this.canvas = null;
this.imageRoot = "";
var drawElipse = function (ctx, x, y, w, h) {
    var kappa = .5522848;
    var ox = (w / 2) * kappa;  // control point offset horizontal
    var oy = (h / 2) * kappa; // control point offset vertical
    var xe = x + w;           // x-end
    var ye = y + h;           // y-end
    var xm = x + w / 2;       // x-middle
    var ym = y + h / 2;       // y-middle

在下面的代码片段中,我创建了一个名为ScientificBox的类,具有两个属性和一个方法(我不太确定这是否是您要求的解决方案)。

    function ScientificBox() {
        this.width = 9;
        this.height = 9;
        this.drawElipse = function () {
            alert(this.width * this.height);
        }
    }

可以用下面的代码调用这个类:

    var box= new ScientificBox();
    box.drawElipse();

我已经测试过了,它可以工作。也许这就是你正在寻找的解决方案?

致以最亲切的问候。

编辑:我忘了展示一个在类上设置属性的代码示例。

    var test = new ScientificBox();
    test.width = 12;
    test.height = 2;
    test.drawElipse();