如何从js中的匿名函数返回值

Tho*_*lby 6 javascript anonymous-function

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

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

 //$id in this scope should be equal 4
Run Code Online (Sandbox Code Playgroud)

小智 2

您必须注意的一件事是您在这里使用异步操作。让我们按精确顺序对行进行编号(n 表示很久以后的某个大数字)

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

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

  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();
Run Code Online (Sandbox Code Playgroud)

2) 示例2

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

function doSomethingWithValue() {
  console.log('myValue is equal to ' + myValue);
}
Run Code Online (Sandbox Code Playgroud)

您还可以研究 $watch,特别是 Angular 在这里为您做了很多工作。