在另一个内部启动一个对象

时间:2011-04-11 23:17:49

标签: javascript object javascript-events canvas

我有一个像这样结构的js软件

obj = new object[id]();

function wrapperFunction (e) {
    var pos = findPos(this);
    e._x = e.pageX - pos.x;
    e._y = e.pageY - pos.y;

    var func = obj[e.type];
    if (func) {
        func(e);            
    }
}

__

obj.line = function () {    
    this.started = false;
    this.mousedown = function (e) {

    }

    this.mousemove = function (e) {
        if (this.started) {

        }
    }

    this.mouseup = function (e) {
        if (this.started) {

        }
    }
}

以上代码块复制多个形状,因此还有obj.square obj.circle等...

我还有一个形状对象,如下所示。

function Shape (type, color, height, width, radius, x, y) {
    this.type = type;
    this.color = color;
    this.h = height;
    this.w = width; 
    this.r = radius;
    this.points = ["x","y"];
    this.points["x"] = [x];
    this.points["y"] = [y];
};

我想在mousedown为每个对象*启动形状对象,并使用propper信息填充形状对象。

现在问题。

radius计算在mousemove以及heightwidth,但是当我向shapes = new Shape(circle, black, 10, 10, null, e._x, e._y)添加mousemove时,{}看起来像......

this.mousemove = function (e) {
    if (this.started) {
        shapes = new Shape(circle, black, 10, 10, null, e._x, e._y);
    }
}

形状对象不会创建。

如果我在包装函数内创建形状对象而不是mousemove,那么对象会启动但我不能使用radiusheight/width。 如何在包装函数内的另一个对象内创建一个对象,以便在创建的对象中使用计算的术语?除了我正在做的事情之外,还有其他途径吗?

1 个答案:

答案 0 :(得分:0)

除了obj = new object[this.id]();行中的烦恼,我认为你只是错过了this个关键字:

this.mousemove = function (e) {
    if (this.started) {
        this.shapes = new Shape(circle, black, 10, 10, null, e._x, e._y);
    }
}

编辑 只是注意到您的代码中有更多的烦恼(是的,这是一个技术术语:)。我想你想在构造函数中更改这些行:

this.points = ["x","y"]; // creates an array, which is indexed by numbers
this.points["x"] = [x];  // tacks on some ad-hoc properties to the array, which
this.points["y"] = [y];  // doesn't really make sense

到此:

this.points = {x: x,   // I think this is what you actually mean to do.
               y: y};