Javascript 试图使用MooTools和Raphael

Javascript 试图使用MooTools和Raphael,javascript,jquery,oop,dom-events,mootools,Javascript,Jquery,Oop,Dom Events,Mootools,我有以下一段代码未按预期运行: var person = new Class({ initialize: function(name) { this.personName = name; alert(this.personName) //WORKS :-) this.testFunc(); //WORKS :-) this.createShape(); /

我有以下一段代码未按预期运行:

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);
        });
    }
});
该警报对click事件不起作用,我理解它的作用,因为它无法访问对象变量“personName”。然而,我想知道是否有可能以某种方式访问它


是否有一个简洁的Javascript小技巧来实现这一点?

createShape
中的
单击
函数中,上下文被设置为
this.personShape.node
不再指代您的
人员
,因此需要对其进行缓存。试试这个:

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);
        });
    }
});

createShape
中的
单击
函数中,上下文被设置为
this.personShape.node
不再指代您的
人员
,因此需要对其进行缓存。试试这个:

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);
        });
    }
});