如何设置全局变量

时间:2018-03-20 10:42:29

标签: javascript angular

export class SharedService { 
isDarkroom = false;

createDarkromInstance(width, height) {
    this.darkroom = new Darkroom('#img', {
        // Size options
        minWidth: 300,
        minHeight: 300,
        maxWidth: 900,
        maxHeight: 900,
        ratio: width/height,
        backgroundColor: '#fff',

        plugins: {
            crop: {
                minHeight: 50,
                minWidth: 50
            },
            save: {
                callback: function() {
                    this.darkroom.selfDestroy();
                    this.imageCroppedBase64 = this.darkroom.canvas.toDataURL();
                    this.isDarkroom = true;
                }
            },
            brush: false
        },

        initialize: function() {
            let cropPlugin =    this.plugins['crop'].requireFocus();
        }
    });
}

如何设置全球" isDarkroom"当我使用this.isDarkrom语言环境变量时,回调函数中的变量被设置。我读了一些关于call()和bind()的内容,但我试图使用但没有成功。

1 个答案:

答案 0 :(得分:3)

尝试将回调更改为胖箭头功能,因为这样可以保持this引用不变:

            callback: () => {
                this.darkroom.selfDestroy();
                this.imageCroppedBase64 = this.darkroom.canvas.toDataURL();
                this.isDarkroom = true;
            }