Could someone explain this to me?
var diagramImage = new Kinetic.Shape(function () {
var context = this.getContext();
context.beginPath();
context.lineWidth = 1;
//This is crazy tricks. It's part of the KineticJS demo website, but how am I able to assign diagramImage.color here?
context.strokeStyle = diagramImage.color;
var lastVertice = polygon.Vertices[polygon.Vertices.length - 1];
context.moveTo(lastVertice.X, lastVertice.Y);
for (var i = 0; i < polygon.Vertices.length; i++) {
var vertice = polygon.Vertices[i];
context.lineTo(vertice.X, vertice.Y);
}
context.stroke();
context.closePath();
});
It seems to me that diagramImage does not exist until the Kinetic constructor returns, but I am able (and seem to need to) assign context’s strokeStyle to diagramImage‘s color — before diagramImage has been created? Why does this work?
EDIT: Full code:
function DrawPolygon(diagramLayer, polygon) {
var diagramImage = new Kinetic.Shape(function () {
var context = this.getContext();
context.beginPath();
context.lineWidth = 2;
//This is crazy tricks. It's part of the KineticJS demo website, but how am I able to assign diagramImage.color here?
context.strokeStyle = diagramImage.color;
var lastVertice = polygon.Vertices[polygon.Vertices.length - 1];
context.moveTo(lastVertice.X, lastVertice.Y);
for (var i = 0; i < polygon.Vertices.length; i++) {
var vertice = polygon.Vertices[i];
context.lineTo(vertice.X, vertice.Y);
}
context.stroke();
context.closePath();
});
diagramImage.color = "red";
diagramImage.on("mouseover", function () {
this.color = "green";
diagramLayer.draw();
});
diagramImage.on("mouseout", function () {
this.color = "red";
diagramLayer.draw();
});
diagramLayer.add(diagramImage);
planViewStage.add(diagramLayer);
}
Because where you are calling
diagramImage.coloris within a closure / function that is passed in to theKinetic.Shapeconstructor. This function is not called / is not executed by the constructor until after the new instance created by the constructor is assigned todiagramImage.Here’s a minimal example that may better explain what’s happening:
As Twisol noted, this can be improved by using
thisinstead. For example:However, as Chris noted, unless documented by the API – there is no guarantee that
thiswill refer toKinetic.Shapeduring the callback – so continuing to usediagramImagehere may still be the better of these 2 options.In short, I think this is not the best API / example / use of JavaScript – and I would not consider this a nuance of JavaScript that you should have to deal with. Sure, these nuances are there if you need them – but you don’t have to.