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