【问题标题】:Attempting To Use MooTools and Raphael尝试使用 MooTools 和 Raphael
【发布时间】:2011-08-12 09:31:30
【问题描述】:

我的以下代码没有按预期运行:

var person = new Class({
    initialize: function(name)
    {
        this.personName = name;
        alert(this.personName)        //WORKS :-)

        this.testFunc();              //WORKS :-)
        this.createShape();           //PAINTS SHAPE BUT CANNOT ACCESS 'personName'
    },
    testFunc() : function()
    {
        alert(this.personName);
    }, 
    createShape() : function()
    {
        this.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"});
        $(this.personShape.node).click(function()
        {

            alert(this.personName);
        });
    }
});

警报不适用于单击事件,我理解它,因为它无法访问对象变量“personName”。但是我想知道是否可以通过某种方式访问​​它?

是否有一个巧妙的 JavaScript 小技巧来实现这一点?

【问题讨论】:

    标签: javascript jquery oop dom-events mootools


    【解决方案1】:

    createShapeclick 函数中,上下文设置为this.personShape.nodethis 不再指代您的 person,因此需要对其进行缓存。试试这个:

    createShape: function() {
        var context = this;
        context.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"});
        $(context.personShape.node).click(function() {
            alert(context.personName);
        });
    }
    

    此外,您的函数不应在类/对象定义中包含括号。此外,出于几个原因,开始将花括号与语句放在同一行是一个好主意。这是我的重构:

    var person = new Class({
        initialize: function(name) {
            this.personName = name;
            alert(this.personName)        //WORKS :-)
    
            this.testFunc();              //WORKS :-)
            this.createShape();
        },
        testFunc: function() {
            alert(this.personName);
        }, 
        createShape: function() {
            var context = this;
            context.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"});
            $(context.personShape.node).click(function() {
                alert(context.personName);
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多