I have the following piece of code which is not running as I expected:
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);
});
}
});
The alert doesn’t work for the click event and I do understand its because it cannot access the object variable ‘personName’. I would however like to know whether or not it is possible to access it in some way?
Would there be a neat little Javascript trick to achieve this?
Inside your
clickfunction increateShape, the context is being set tothis.personShape.node.thisno longer refers to yourpersonso it needs to be cached. Try this:Also, your functions shouldn’t have parenthesis in your Class/object definition. Also, it’s a good idea to start putting your curly braces on the same line as your statement for a few reasons. Here’s my refactor: