Question

I'm writing a function in JS, but I have a problem with the variabile marker.

The code:

    function piano(numero, link) {

            var marker;
            this.marker = marker;

            var immagine = loadImage(link, marker);
            this.immagine = immagine


            function createMarker() {

                    return new RichMarker({

                           ....

                    });
            }

            function loadImage(link, marker) {

                    var immagine = new Image();

                    immagine.src = link;

                    immagine.onload = function() {
                            marker = createMarker();  
                    };  

                    return immagine;
             }

             ....

The variabile immagine is initialized calling the function loadImage for the loading of the picture.

In this function it's the code:

                    immagine.onload = function() {
                            marker = createMarker();  
                    };  

which have to do the assignment of marker after the loading of the image.

When I try to access to marker, after the loading of the image, it always result undefined; and I know for sure that the RichMarker has been created.

I don't understand why it's happening this.

Was it helpful?

Solution

JavaScript variables will store a reference to an object, but you can't share a reference to say a Number or String or undefined. If marker is anything but an array or object, then marker and this.marker will not be the same object when you modify it later (think of it as copying the value, instead of assigning the reference).

Instead try scoping the this object, so later you can reference that object again:

function piano(numero, link) {
    var self = this;
    this.immagine = loadImage(link);


    function createMarker() {
        return new RichMarker({
            //...
        });
    }

    function loadImage(link) {
        var immagine = new Image();
        immagine.src = link;

        immagine.onload = function() {
            //use the scoped version of 'this'
            self.marker = createMarker();  
        };  

        return immagine;
     }

     //...
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top