JavaScript 保存这个。image.onLoad 中的变量

Ray*_*den 3 javascript object

function InfoImage(path,title){
    this.path = path;
    this.title = title;
    this.color = undefined;
    this.maxPixels = undefined;

    this.init = function(){
        var canvas = document.querySelector("canvas");
        var img_Color = new Image_Processing_Color(canvas);
        var img = new Image();
        img.onload = function () {
            img_Color.init(img);
            this.color = img_Color.getDominantColor(); //this doesnt work
            this.maxPixels = img_Color.getDominantColorPixels();
        };
        img.src = path;
    };


    this.init();
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我如何将这些变量保存为 InfoImage 变量?我知道在this那里使用会影响 Image 而不是 InfoImage ...

T.J*_*der 7

如果我理解正确,通常的答案是使用变量来引用thisinit然后关闭:

function InfoImage(path,title){
    this.path = path;
    this.title = title;
    this.color = undefined;
    this.maxPixels = undefined;

    this.init = function(){
        var canvas = document.querySelector("canvas");
        var img_Color = new Image_Processing_Color(canvas);
        var img = new Image();
        var infoimg = this;                                         // <===

        img.onload = function () {
            img_Color.init(img);
            infoimg.color = img_Color.getDominantColor();           // <===
            infoimg.maxPixels = img_Color.getDominantColorPixels(); // <===
        };
        img.src = path;
    };
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用Function#bind

function InfoImage(path,title){
    this.path = path;
    this.title = title;
    this.color = undefined;
    this.maxPixels = undefined;

    this.init = function(){
        var canvas = document.querySelector("canvas");
        var img_Color = new Image_Processing_Color(canvas);
        var img = new Image();

        img.onload = function () {
            img_Color.init(img);
            this.color = img_Color.getDominantColor();
            this.maxPixels = img_Color.getDominantColorPixels();
        }.bind(this);                                             // <===
        img.src = path;
    };
}
Run Code Online (Sandbox Code Playgroud)

在 ES6(JavaScript 的下一个版本)中,您将能够使用箭头函数,因为与普通函数不同,箭头函数this从定义它们的上下文中继承它们的值:

function InfoImage(path,title){
    this.path = path;
    this.title = title;
    this.color = undefined;
    this.maxPixels = undefined;

    this.init = function(){
        var canvas = document.querySelector("canvas");
        var img_Color = new Image_Processing_Color(canvas);
        var img = new Image();

        img.onload = () => {                              // <===
            img_Color.init(img);
            this.color = img_Color.getDominantColor();
            this.maxPixels = img_Color.getDominantColorPixels();
        };
        img.src = path;
    };
}
Run Code Online (Sandbox Code Playgroud)