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();
}
在这个例子中,我如何将这些变量保存为 InfoImage 变量?我知道使用this
将会影响 Image 而不是 InfoImage...
如果我没理解错的话,通常的答案是使用变量来引用this
, which init
然后关闭:
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;
};
}
您还可以使用Function#bind http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.5:
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;
};
}
在 JavaScript 的下一版本 ES6 中,您将能够使用箭头函数,因为与普通函数不同,箭头函数继承了它们的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;
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)