0

I am trying to implement my own object in Javascript. I am using the protype method to add the the objects and it's methods. what I do is the following

function MyCustomObject(){

    this.attr1 = value;
    //more atributes here. This works fine
    this.options = {
        imageFilenames: ['image1.png', 'image2.png',...],
        baseUrl:'url;'
    };
    this.objectMethod();
}


MyCustomObject.prototype.objectMethod = function (){
    //..... method's body here.
    var url = this.options.url; 
    this.options.imageFilenames.forEach(function (filename, index){

        var src = url+'/'+filename;
        imageObj = new Image();
        imageObj.src  = src;
        imageObj.load = function (){

            image = new Kinetic.Image({
                x:0,
                y:0,
                id: filename,
                width: imageObj.width,
                height: imageObj.height,
                image:imageObj
            });
            this.imageObjects[index] = imageObj;
            this.teethImages[index] = image;

        };

        if (this.imageObjects.length === this.options.imageFilenames.length){
            this.positionImages();
            this.createLineGroups();
            this.createLabelGroups()
            this.createStage();
            this.drawOnScreen();
        }

    });

}

My problem is that when I am trying to use this keyword inside the forEach function then this is the options object and not MyCustomObject. How can I bypass this behaviour?

Apostolos
  • 7,763
  • 17
  • 80
  • 150

1 Answers1

0

Simple solution :

var obj = this,
    url = obj.options.url; 
obj.options.imageFilenames.forEach(function (filename, index){ 
    // use obj instead of this here

You'll soon be able to use the ES6 arrow notation :

obj.options.imageFilenames.forEach((filename, index) => { 
    // external this unchanged

(this already works in Firefox and Chrome)

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758