0

我正在尝试将一个对象从它自己的对象发送到另一个对象。

var Tile = new Class({
    initialize : function(){
        this.inner = new Element(...);
        this.inner.addEvent('click', function() {
            popup.open(this);
        });
    }
});

如果我从 Tile out op Popup 警告任何成员变量,它会警告“未定义”。我究竟做错了什么?

var Popup = new Class({
    initialize : function(){
    },
    open : function(tile) {
        alert(tile.width);
    }
});

亲切的问候!

4

2 回答 2

2

当您传递thispopup对象时,您正在传递元素本身(我相信这是您的意图)。但是,默认情况下,元素没有名为width.

也许您正在寻找getSize();?这将返回一个具有两个属性的对象(xy),分别对应于元素的宽度和高度。

我已将您的代码近似为以下 jsFiddle,试一试:http: //jsfiddle.net/g4SmJ/

作为参考,这里是新的Popup类代码:

var Popup = new Class({
    initialize : function(){
    },
    open : function(tile) {
        size = tile.getSize();
        console.log(size);    // console.log provides a nicer interface for debugging, you can pass objects into it! Use the Chrome Inspector or Firebug to see its output.
        alert(size.x);
    }
});

回应您的评论:

哦,我并不是要提醒doms宽度,对此感到抱歉。我发布的是完整对象中的较小代码。Width 实际上是 Tiles 中定义的成员,我想从 Popup 中提醒

在这种情况下,当您向 发送调用时.open();,您传入this了函数调用,但没有传递Tile对象!相反,您传递了inner您创建的元素。

如此重写Tile

var Tile = new Class({
    initialize : function(){
        var self = this;
        this.inner = new Element(...);
        this.inner.addEvent('click', function() {
            popup.open(self);
        });
    }
});
于 2013-04-02T16:17:37.480 回答
1

我猜你正在寻找发送Tile实例。像上面的答案一样 - 当您发送thisinsideaddEvent方法时,您发送的是调用事件的元素本身:在您的情况下,您发送的是 inner 实例,因为您在其上定义了 onclick。

如果您想发送 tile 实例,您有 2 个选项:

1) 绑定到函数 this - 意味着将您所在的当前范围(Tile)“连接”到事件中:

var Tile = new Class({
    initialize : function(){
        this.inner = new Element(...);
        this.inner.addEvent('click', function() {
            popup.open(this); // <- now this is 'Tile' instance 
        }.bind(this)); //bind this to click
    }
});

2)将实例保存在函数范围之外并在内部使用:

var Tile = new Class({
    initialize : function(){
        this.inner = new Element(...);
        var self = this; //save the this to var 'self'
        this.inner.addEvent('click', function() {
            popup.open(self); //use self which holds the Tile instance
        });
    }
});
于 2013-04-02T16:45:53.087 回答