图片未定义onload函数,需要获取高宽
image undefined onload function, need to get height and width
我得到了这个代码:
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = () => {
alert(JSON.stringify(img));
alert(this.height);
alert(this.width);
};
img.src = ImageURL;
}
应该加载googlechrome中的图片,并获取图片的高宽。为什么对象 returns 为空?
this
没有指向你在箭头函数中需要的东西
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = function() { // now "this" will be what you think it is
console.log(this.height,this.width);
};
img.src = ImageURL;
}
_getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")
带箭头:
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = (e) => { // now you can use e.target
console.log(e.target.height,e.target.width);
};
img.src = ImageURL;
}
_getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")
问题是您在 ES6 箭头函数中使用 this
。它与经典的 JS 函数有不同的上下文。您必须使用此代码才能正常工作:
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = function () {
alert(JSON.stringify(img));
alert(this.height);
alert(this.width);
};
img.src = ImageURL;
}
我得到了这个代码:
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = () => {
alert(JSON.stringify(img));
alert(this.height);
alert(this.width);
};
img.src = ImageURL;
}
应该加载googlechrome中的图片,并获取图片的高宽。为什么对象 returns 为空?
this
没有指向你在箭头函数中需要的东西
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = function() { // now "this" will be what you think it is
console.log(this.height,this.width);
};
img.src = ImageURL;
}
_getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")
带箭头:
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = (e) => { // now you can use e.target
console.log(e.target.height,e.target.width);
};
img.src = ImageURL;
}
_getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")
问题是您在 ES6 箭头函数中使用 this
。它与经典的 JS 函数有不同的上下文。您必须使用此代码才能正常工作:
_getWidthAndHeight = (ImageURL) => {
var img = new Image();
img.onload = function () {
alert(JSON.stringify(img));
alert(this.height);
alert(this.width);
};
img.src = ImageURL;
}