如何从我传入的预定义回调中访问外部变量?

时间:2022-04-07 23:18:18

So I have this code which just sorts a product list by price or anything the user wants and it works:

所以我有这个代码只是按价格或用户想要的任何东西对产品列表进行排序,它的工作原理如下:

var sortProductsBy = function(products, sortType){
  //sort type is a string, it could be 'price'
  products.sort(function (product1, product2) {

    var product1AttrValue  = parseInt( $(product1).attr(sortType).replace('$','') );
    var product2AttrValue  = parseInt( $(product2).attr(sortType).replace('$','') );

    if (product1AttrValue < product2AttrValue ) {
      return -1;
    }
    if (product1AttrValue > product2AttrValue) {
      return 1;
    }
    return 0;// product1 must be equal to product2
  })
};

The sort functions callback which I'm defining as an argument to my sort function is quite long so I wanted to decouple it, define it elsewhere, and the pass in my sort function like so:

我定义为sort函数的参数的sort函数回调很长,所以我想将它解耦,在别处定义它,并在我的sort函数中传递如下:

var sortProductsBy = function(products, sortType){
  //I need compareFunc to somehow have access to sortType
    products.sort(compareFunc)
}

I need my compareFunc to somehow have access to sortType variable that get's passed in, but due to scope I want have access to it. Is there a way I could somehow gain access to it without having to define my entire callback like in the first code snippet?

我需要我的compareFunc以某种方式访问​​传入的sortType变量,但由于我希望有范围访问它。有没有办法我可以以某种方式获得访问权限,而不必像在第一个代码片段中那样定义我的整个回调?

2 个解决方案

#1


1  

If you have function compareFunc (sortType, a, b) {}:

如果你有函数compareFunc(sortType,a,b){}:

var sortProductsBy = function (products, sortType) {
  products.sort(compareFunc.bind(null, sortType));
}

See: .bind

#2


-1  

Calling compareFunc from the callback would work.

从回调中调用compareFunc会起作用。

function compareFunc(sortType) {
  // use sortType
}

var sortProductsBy = function(products, sortType){
  //I need compareFunc to somehow have access to sortType
  products.sort(function() {
    compareFunc(sortType);
  });
}

Also, have a look at the JavaScript functions bind() and call() and experiment with how you might use those, for fun.

另外,看看JavaScript函数bind()和call(),并试验如何使用它们,以获得乐趣。

#1


1  

If you have function compareFunc (sortType, a, b) {}:

如果你有函数compareFunc(sortType,a,b){}:

var sortProductsBy = function (products, sortType) {
  products.sort(compareFunc.bind(null, sortType));
}

See: .bind

#2


-1  

Calling compareFunc from the callback would work.

从回调中调用compareFunc会起作用。

function compareFunc(sortType) {
  // use sortType
}

var sortProductsBy = function(products, sortType){
  //I need compareFunc to somehow have access to sortType
  products.sort(function() {
    compareFunc(sortType);
  });
}

Also, have a look at the JavaScript functions bind() and call() and experiment with how you might use those, for fun.

另外,看看JavaScript函数bind()和call(),并试验如何使用它们,以获得乐趣。