簡體   English   中英

如何從js中的匿名函數返回值

[英]How to return value from anonymous function in js

我想從匿名函數返回值。 如何在下面的代碼中將返回值分配給 $id 變量?

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

 //$id in this scope should be equal 4

您需要指定到達 asyn 函數或操作時要執行的操作,因此通常使用回調時的返回是另一個回調...

function aux(param1, callback){
    // do whatever...
    $(document).on("click", param1, function(e) {
        // return 4;
        callback(4);
    });
}

你會在你的代碼中使用它,如下所示:

// your context..
// operations 1.. 2..
aux('.delete-component', function(theReturnedValue){
    console.log(theReturnedValue); // 4
});

這就是回調將值“返回”到外部作用域的方式。

您必須注意的一件事是您在這里使用異步操作。 讓我們按嚴格的順序對行進行編號(n 表示遠在很久以后的某個高數)

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

您所做的是附加偵聽器以單擊。 目前不會發生點擊 - 當有人點擊時會發生。 因此,您將可以在點擊后訪問它。 你可以做兩件事:

  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 在這里為你做了很多工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM