如何从js中的匿名函数返回值 [英] How to return value from anonymous function in js

查看:82
本文介绍了如何从js中的匿名函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从匿名函数返回值.如何在下面的代码中将返回值分配给 $id 变量?

I would like to return value from anonymous function. How can I assign returned value to $id variable in below code ?

$(document).on("click", '.delete-component', function(e) {
     return 4;
 });

 //$id in this scope should be equal 4

推荐答案

在使用异步操作时,您必须注意一件事.让我们按照严格的顺序对行进行编号(n 表示更晚一些的高数)

One thing you have to be aware that you work here with asynchronous actions. Let's number lines in order of exaction (n means some high number far far later)

1]    $(document).on("click", '.delete-component', function(e) {
n+1]    return 4;
      });
2]    console.log('here');

您所做的是附加侦听器以单击.目前不会发生点击 - 当有人点击时会发生.因此,您将可以在点击后访问它.你可以做两件事:

What you did was attached listener to click. Click won't happen at the moment - it will happen when someone clicks. Therefore you will have access to it after click happens. You can do two things:

  1. 在上述范围内声明 var.
  2. 将值转发给回调

1) 示例 1

var myValue = 0;
$(document).on("click", '.delete-component', function(e) {
     myValue = 4;
});

function abc() {
  console.log('myValue is equal to ' + myValue);
}

// if that line happen before clicking, value will be still 0
execture somewhen abc();

2) 示例 2

$(document).on("click", '.delete-component', function(e) {
     doSomethingWithValue(4);
});

function doSomethingWithValue() {
  console.log('myValue is equal to ' + myValue);
}

您也可以调查 $watch,尤其是 Angular 在这里为您做了很多工作.

You can also investigate $watch, especially Angular does here a lot work for you.

这篇关于如何从js中的匿名函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆