结果是一个数字。因此它返回值9
不是对象的引用。
bind
在您的方案中没有任何有用的效果。 bind
更改函数上下文(this
)。
返回包含值10的对象将起作用。
var f1 = function(){
var result = { value: 9 };
window.setTimeout(
function(){
console.log("timeout in 100ms");
result.value = 10;}.bind(this), 100);
return result;
};
有可能是您的问题更好的解决方案。
回调:
var f1 = function(valueCallback){
var result;
window.setTimeout(function(){
console.log("timeout in 100ms");
result = 10;
valueCallback(result);
};
这样的功能将被用于像这样:
f1(function(value)) {
console.log(value); // Will print 10 after 100ms.
})
另一种选择,可以使用承诺:
var f1 = function() {
return new Promise(function(resolve, reject) {
window.setTimeout(resolve.bind(null, 10), 100);
}
}
你会打电话SUC HA功能,像这样:
f1().then(function(value) {
console.log(value); // Will print 10 after 100ms.
});
[为什么是我的变量不变后,我修改它的内部函数?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –
[我如何返回来自异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –
'.bind(this)'has没有相关性e变量;只会影响'this'关键字的值。而且,如果您因此收到“9”,您的片段似乎缺乏一些东西。 –