javascript在对象构造函数中运行对象方法

时间:2014-10-13 14:09:50

标签: javascript javascript-objects

我正在尝试在Javascript中实现自己的对象。我正在使用protype方法添加对象及其方法。我所做的是以下

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

    });

}

我的问题是,当我尝试在forEach函数中使用此关键字时,这是选项对象而不是MyCustomObject。我该如何绕过这种行为?

1 个答案:

答案 0 :(得分:0)

简单的解决方案:

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

您很快就可以使用ES6箭头符号:

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

(这已在Firefox和Chrome中有效)

相关问题