javascript - 如何将变量分配给回调?
问题描述
我有这个函数,它需要一个 URL 和回调:
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { return callback(this.width, this.height); }
}
这个回调函数是这样调用的:(这有效并警告正确的输出前 100px , 100px)
getMeta(
i_url, //This being the URL (in base64 or real web url)
function(width, height) { alert(width + 'px ' + height + 'px') }
);
但是,每当我尝试为其分配一个变量并切换返回警报时,我都会得到未定义的..
const test = getMeta(
i_url,
function(width, height) { return width + 'px ' + height + 'px' }
);
alert(test);
警报消息:未定义
解决方案
您没有在getMeta
方法内返回任何值,您只从回调中返回,该回调永远不会从对方法的原始调用中传递出来getMeta
。
按照这个代码,看看你是否明白
function getMeta(url, callback) {
var img = new Image();
img.src = url;
/*
This return is only assigned to img.onload
But this assignment does not make any sense.
*/
// img.onload = function() { return callback(this.width, this.height); }
/* if you want to use the image height and width inside your own logic you can include that logic in the callback */
img.onload = function() { callback(this.width, this.height) }
// maybe you can return the IMG from this method
return img;
}
您可以声明一个全局对象并从回调中引用宽度和高度
let imageMeta = {height: null, width: null}
getMeta(
i_url,
function(width, height) { imageMeta.width = width; imageMeta.height = height }
);
如果您想要一个更强大的解决方案,您应该研究Promise
推荐阅读
- python - 关于如何从本网站抓取数据的建议
- mql4 - OrderSend mq4 ea
- java - 如何在android studio中更改一组按钮中的选定按钮背景
- php - 如果用户在过去 60 天内未在 codeigniter 中登录,则重定向到重置密码页面
- r - tidyverse 在给定一系列键的情况下在数据框中查找值的方法
- java - java Windows 服务如何“知道”它已完成初始化?
- r - 将数据从单个观察重新排列为多个
- xml - DBMS_XMLQUERY 与 DBMS_XMLGEN:任何替代 DBMS_XMLQUERY.seterrortag(sqlcontext, 'Any_Tag_Name')
- python - tensorflow 对象检测 API train.py 自身错误
- ibm-mq - IBM MQ - 能够在维护期间对消息进行排队,而无需停止通道